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

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

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

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

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


当前回答

规范里没有,没有。主要的区别在于程序员在2年内阅读你的代码时的期望。结构体通常被假定为POD。当您为定义对象以外的目的定义类型时,也会在模板元编程中使用结构。

其他回答

类和结构之间的区别是关键字之间的区别,而不是数据类型之间的区别。这两个

struct foo : foo_base { int x;};
class bar : bar_base { int x; };

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

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

引用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和class之间的主要区别是,在struct中只能声明不同数据类型的数据变量,而在class中可以声明数据变量和成员函数,因此可以通过函数操作数据变量。

-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it . while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..

但这取决于程序员认为哪种方式合适……对我来说,我更喜欢类,因为它支持oop,这就是它几乎在所有语言中实现的原因,它是所有编程的美妙特性;-)

是的,我忘记提到的最令人难忘的区别是类支持数据隐藏,也支持在内置数据类型上执行的操作,而struct不支持!

c++的起源和与C的兼容性是值得记住的。

C语言有结构体,它没有封装的概念,所以一切都是公共的。

在采用面向对象的方法时,默认为public通常被认为是一个坏主意,所以在编写一种原生有利于OOP(你可以在C中做OO,但它不会帮助你)的C形式时,这是c++(最初是“C With Classes”)的想法,默认为private成员是有意义的。

另一方面,如果Stroustrup改变了struct的语义,使其成员默认为私有,那么就会破坏兼容性(随着标准的分歧,这种情况不再经常发生,但所有有效的C程序也是有效的c++程序,这对c++的立足点有很大影响)。

因此引入了一个新的关键字class,它与struct完全相似,但默认为private。

如果c++从零开始,没有历史,那么它可能只有一个这样的关键字。它也可能不会产生这样的影响。

一般来说,人们在做类似C语言中使用结构体的事情时,会倾向于使用结构体;公共成员,没有构造函数(只要它不在联合中,你可以在结构中有构造函数,就像类一样,但人们倾向于不这样做),没有虚方法,等等。因为语言既可以用来指导机器,也可以用来与阅读代码的人交流(否则我们就会坚持使用汇编和原始VM操作码),所以坚持使用它是个好主意。

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