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

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

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

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

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


当前回答

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

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

其他回答

引用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 foo : foo_base { int x;};
class bar : bar_base { int x; };

两者都定义了一个类类型。这里关键字的区别在于默认访问权限的不同:

Foo::x是公共的,foo_base是公共继承的 Bar::x是私有的,bar_base是私有继承的

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

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

类的成员默认为private。Struct的成员默认为public。除此之外,没有其他区别。还有这个问题。

其他答案提到了private/public默认值(但请注意,struct是类是struct;它们不是两个不同的项目,只是同一项目的两种定义方式)。

值得注意的是(特别是因为请求者提到“非托管”c++,所以很可能正在使用msvc++),在某些情况下,如果一个类用class声明,然后用struct定义(或者可能相反),visualc++会抱怨,尽管标准说这是完全合法的。