这个问题已经在c# /. net上下文中提出过了。

现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。

我将从一个明显的区别开始:

如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。

我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。


当前回答

另一件需要注意的事情是,如果你更新了一个有结构的遗留应用程序来使用类,你可能会遇到以下问题:

旧代码有结构,代码被清理,这些被更改为类。 然后将一两个虚函数添加到新更新的类中。

当虚函数在类中时,编译器会在内部添加额外的指针指向类数据,以指向函数。

这将如何打破旧的遗留代码是,如果在旧代码中的某个地方使用memfill将结构清除为零,这也将破坏额外的指针数据。

其他回答

引用c++ FAQ,

[7.8] What's the difference between the keywords struct and class? The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults. Struct and class are otherwise functionally equivalent. OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

另一件需要注意的事情是,如果你更新了一个有结构的遗留应用程序来使用类,你可能会遇到以下问题:

旧代码有结构,代码被清理,这些被更改为类。 然后将一两个虚函数添加到新更新的类中。

当虚函数在类中时,编译器会在内部添加额外的指针指向类数据,以指向函数。

这将如何打破旧的遗留代码是,如果在旧代码中的某个地方使用memfill将结构清除为零,这也将破坏额外的指针数据。

c++中struct和class关键字的区别在于,当在特定的复合数据类型上没有特定的说明符时,默认情况下struct或union是只考虑隐藏数据的公共关键字,而class是考虑隐藏程序代码或数据的私有关键字。总是有一些程序员为了数据而使用结构,为了代码而使用类。欲了解更多信息,请联系其他渠道。

另一个主要区别是模板。据我所知,你可以在定义模板时使用类,但不能定义结构。

template<class T> // OK
template<struct T> // ERROR, struct not allowed here

你忘记了类和结构之间棘手的第二个区别。

引用标准(§11.2.2在c++ 98到c++ 11):

在没有访问说明符时 对于基类,假定为public 当声明派生类时 Struct和private在类声明为class时被假设。

为了完整起见,更广为人知的class和struct之间的区别定义在(11.2)中:

类定义的类的成员 关键字类private by 违约。定义的类的成员 使用关键字struct或union 默认为public。

另一个区别是:关键字class可以用来声明模板参数,而struct关键字不能这样使用。