这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
这个问题已经在c# /. net上下文中提出过了。
现在我想学习c++中结构体和类的区别。请讨论在OO设计中选择一种或另一种的技术差异以及原因。
我将从一个明显的区别开始:
如果没有指定public:或private:,结构体的成员默认为public;默认情况下,类的成员是私有的。
我敢肯定,在c++规范的晦涩角落里还会发现其他不同之处。
当前回答
你忘记了类和结构之间棘手的第二个区别。
引用标准(§11.2.2在c++ 98到c++ 11):
在没有访问说明符时 对于基类,假定为public 当声明派生类时 Struct和private在类声明为class时被假设。
为了完整起见,更广为人知的class和struct之间的区别定义在(11.2)中:
类定义的类的成员 关键字类private by 违约。定义的类的成员 使用关键字struct或union 默认为public。
另一个区别是:关键字class可以用来声明模板参数,而struct关键字不能这样使用。
其他回答
你忘记了类和结构之间棘手的第二个区别。
引用标准(§11.2.2在c++ 98到c++ 11):
在没有访问说明符时 对于基类,假定为public 当声明派生类时 Struct和private在类声明为class时被假设。
为了完整起见,更广为人知的class和struct之间的区别定义在(11.2)中:
类定义的类的成员 关键字类private by 违约。定义的类的成员 使用关键字struct或union 默认为public。
另一个区别是:关键字class可以用来声明模板参数,而struct关键字不能这样使用。
另一个主要区别是模板。据我所知,你可以在定义模板时使用类,但不能定义结构。
template<class T> // OK
template<struct T> // ERROR, struct not allowed here
类的成员默认为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;
}
根据c++编程语言中的Stroustrup:
你使用哪种风格取决于环境和品味。对于所有数据都是公共的类,我通常更喜欢使用struct。我认为这样的类“不是很合适的类型,只是数据结构”。
在功能上,除了public / private没有区别
规范里没有,没有。主要的区别在于程序员在2年内阅读你的代码时的期望。结构体通常被假定为POD。当您为定义对象以外的目的定义类型时,也会在模板元编程中使用结构。