C++中struct和class有什么区别? [英] What are the differences between struct and class in C++?

查看:36
本文介绍了C++中struct和class有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是已经在 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):

定义的类的成员关键字 classprivate 由默认.定义的类的成员使用关键字 structunion默认情况下是公开.

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++中struct和class有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆