这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
当前回答
另一个主要区别是模板。据我所知,你可以在定义模板时使用类,但不能定义结构。
template<class T> // OK
template<struct T> // ERROR, struct not allowed here
其他回答
您可以将此作为何时使用struct或class的指导方针,https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx。
的实例,考虑定义一个结构体而不是类 类型小,通常寿命短或通常嵌入 其他对象。 避免定义结构体,除非该类型具有所有的 以下特点: 它在逻辑上代表一个值, 类似于基本类型(int, double等)。 它有一个实例 大小小于16字节。 它是不可变的。 它不必被装箱 频繁。
虽然其他答案暗示了这一点,但并没有明确提到——结构体是与C兼容的,这取决于用法;课程不是。
这意味着如果你想要编写一个与C兼容的头文件,那么除了struct(在C世界中不能有函数;但可以有函数指针)。
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.
你忘记了类和结构之间棘手的第二个区别。
引用标准(§11.2.2在c++ 98到c++ 11):
在没有访问说明符时 对于基类,假定为public 当声明派生类时 Struct和private在类声明为class时被假设。
为了完整起见,更广为人知的class和struct之间的区别定义在(11.2)中:
类定义的类的成员 关键字类private by 违约。定义的类的成员 使用关键字struct或union 默认为public。
另一个区别是:关键字class可以用来声明模板参数,而struct关键字不能这样使用。
. 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.