这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
当前回答
结构和类之间有3个基本区别
第1 -内存是为堆栈内存中的结构保留的(这接近于编程语言),无论堆栈内存中的类是仅为引用保留的,实际内存是在堆内存中保留的。
默认情况下,结构对待公共类是否对待私有类。
第三,不能在结构中重用代码,但在类中我们可以多次重用相同的代码,称为继承
其他回答
另一个主要区别是模板。据我所知,你可以在定义模板时使用类,但不能定义结构。
template<class T> // OK
template<struct T> // ERROR, struct not allowed here
类的成员默认为private。Struct的成员默认为public。除此之外,没有其他区别。还有这个问题。
这只是一种惯例。可以创建结构来保存简单的数据,但稍后会随着成员函数和构造函数的添加而发展。另一方面,在struct中看到public: access之外的东西是不寻常的。
类和结构之间的区别是关键字之间的区别,而不是数据类型之间的区别。这两个
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.