What are the differences between struct and class in C++?(C ++中的结构和类有什么区别?)
问题描述
这个问题已经在 C#/.Net 的上下文中提出.
现在我想了解 C++ 中结构和类之间的区别.请讨论技术差异以及在 OO 设计中选择其中一种的原因.
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
我将从一个明显的区别开始:
I'll start with an obvious difference:
- 如果不指定
public:
或private:
,则结构的成员默认为public;默认情况下,类的成员是私有的.
- If you don't specify
public:
orprivate:
, members of a struct are public by default; members of a class are private by default.
我确信在 C++ 规范的晦涩角落中还有其他差异.
I'm sure there are other differences to be found in the obscure corners of the C++ specification.
推荐答案
你忘记了类和结构之间棘手的第二个区别.
You forget the tricky 2nd difference between classes and structs.
引用标准(C++98 到 C++11 中的第 11.2.2 节):
Quoth the standard (§11.2.2 in C++98 through C++11):
如果没有访问说明符对于基类,假定为 public声明派生类时struct 和 private 在声明类时假定为 class.
In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.
为了完整起见,类和结构之间更广为人知的区别在 (11.2) 中定义:
And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):
定义的类的成员关键字 class 是 private 的默认.定义的类的成员使用关键字 struct 或 union默认是公开的.
Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.
另外的区别:关键字class
可以用来声明模板参数,而struct
关键字不能这样使用.
Additional difference: the keyword class
can be used to declare template parameters, while the struct
keyword cannot be so used.
这篇关于C ++中的结构和类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++中的结构和类有什么区别?
基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01