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

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

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

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

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


当前回答

引用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.

其他回答

我发现了另一个不同。如果在类中没有定义构造函数,编译器将定义一个。但是在struct中,如果你没有定义构造函数,编译器也不会定义构造函数。因此,在某些情况下,我们确实不需要构造函数,struct是一个更好的选择(性能技巧)。 对不起,我的英语不好。

还有一个不成文的规则告诉我们: 如果类的数据成员与自身没有关联,则使用struct。 如果数据成员的值依赖于另一个数据成员的值,则使用class。

f.e

class Time
{
    int minutes;
    int seconds;
}

struct Sizes
{
    int length;
    int width;
};

STRUCT是一种抽象数据类型,它根据结构规范划分给定的内存块。结构体在文件序列化/反序列化中特别有用,因为结构体通常可以被逐字写入文件。(例如,获取一个指向结构的指针,使用SIZE宏计算要复制的字节数,然后将数据移进或移出结构。)

类是一种不同类型的抽象数据类型,试图确保信息隐藏。在内部,可以有各种各样的诡计,方法,临时变量,状态变量。等等,它们都被用来为任何希望使用该类的代码提供一致的API。

实际上,结构体是关于数据的,类是关于代码的。

但是,您确实需要理解这些仅仅是抽象。创建看起来很像类的结构体和看起来很像结构体的类是完全可能的。事实上,最早的c++编译器只是将c++代码转换为C的预编译器。因此,这些抽象有助于逻辑思维,而不一定是计算机本身的资产。

Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.

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

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

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