这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
当前回答
您可以将此作为何时使用struct或class的指导方针,https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx。
的实例,考虑定义一个结构体而不是类 类型小,通常寿命短或通常嵌入 其他对象。 避免定义结构体,除非该类型具有所有的 以下特点: 它在逻辑上代表一个值, 类似于基本类型(int, double等)。 它有一个实例 大小小于16字节。 它是不可变的。 它不必被装箱 频繁。
其他回答
类的成员默认为private, struct的成员默认为public。
例如,程序1编译失败,程序2运行正常。
// Program 1
#include <stdio.h>
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
从类/结构派生结构时,基类/结构的默认访问说明符为public。派生类时,默认访问说明符为private。
例如,程序3编译失败,程序4工作正常。
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error because inheritance is private
getchar();
return 0;
}
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine because inheritance is public
getchar();
return 0;
}
. 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.
其他答案提到了private/public默认值(但请注意,struct是类是struct;它们不是两个不同的项目,只是同一项目的两种定义方式)。
值得注意的是(特别是因为请求者提到“非托管”c++,所以很可能正在使用msvc++),在某些情况下,如果一个类用class声明,然后用struct定义(或者可能相反),visualc++会抱怨,尽管标准说这是完全合法的。
结构和类之间有3个基本区别
第1 -内存是为堆栈内存中的结构保留的(这接近于编程语言),无论堆栈内存中的类是仅为引用保留的,实际内存是在堆内存中保留的。
默认情况下,结构对待公共类是否对待私有类。
第三,不能在结构中重用代码,但在类中我们可以多次重用相同的代码,称为继承
Iso iec14882 -2003 9类 §3 结构是用定义的类 类键结构体;它的成员 基类(第10条)是 默认为公开(第11条)。