C ++中的结构和类有什么区别?

2022-01-30 00:00:00 class oop struct c++ c++-faq

这个问题已经在 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: or private:, 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.

相关文章