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

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

问题描述

这个问题是在C#/。Net 上下文中提出的问题。

This question was already asked in the context of 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.

Quoth the standard(§11.2.2in C ++ 98 to C ++ 11):

Quoth the standard (§11.2.2 in C++98 through C++11):


em> access-specifier
表示基类,public表示为
,当派生类被声明为
struct

为了完整起见,类和struct在(11.2)中定义:

And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):



关键字定义的类的成员默认情况下,
的默认值为 private 。默认情况下,用关键字 struct union
定义
类的成员是 public

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

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