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

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

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

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

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


当前回答

这只是一种惯例。可以创建结构来保存简单的数据,但稍后会随着成员函数和构造函数的添加而发展。另一方面,在struct中看到public: access之外的东西是不寻常的。

其他回答

默认情况下,用关键字class定义的类的成员为private。用关键字struct(或union)定义的类的成员默认是公共的。 在基类没有访问说明符的情况下,当派生类声明为struct时假定为public,当类声明为class时假定为private。 你可以使用模板<类T>,但不能使用模板<结构T>。

还要注意,c++标准允许将类型前向声明为struct,然后在声明类型时使用class,反之亦然。同样,std::is_class<Y>::value对于Y是一个结构和类是true,但是对于枚举类是false。

. In classes all the members by default are private but in structure members are public by default. There is no term like constructor and destructor for structs, but for class compiler creates default if you don't provide. Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should typically be used for grouping data. The class default access type is private, and the default mode for inheritance is private. A class should be used for grouping data and methods that operate on that data. In short, the convention is to use struct when the purpose is to group data, and use classes when we require data abstraction and, perhaps inheritance. In C++ structures and classes are passed by value, unless explicitly de-referenced. In other languages classes and structures may have distinct semantics - ie. objects (instances of classes) may be passed by reference and structures may be passed by value. Note: There are comments associated with this question. See the discussion page to add to the conversation.

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

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

综上所述,我们可以得出结论,概念Class比“Structures”更适合代表现实世界中的对象。很大程度上是因为在课堂上使用的面向对象的概念在解释现实场景时非常实用,因此更容易将它们合并到现实中。例如,对于结构体,默认继承是公共的,但如果我们将此规则应用于现实世界,那就太荒谬了。但在类中,默认继承是私有的,这更现实。

无论如何,我需要证明的是类是一个更广泛的,现实世界适用的概念,而结构是一个原始的概念,具有糟糕的内部组织(即使结构遵循面向对象的概念,他们有一个糟糕的含义)

这只是一种惯例。可以创建结构来保存简单的数据,但稍后会随着成员函数和构造函数的添加而发展。另一方面,在struct中看到public: access之外的东西是不寻常的。