在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
我从来不在c++中使用struct。
我无法想象在需要私有成员时使用结构体的场景,除非您故意试图混淆。
使用结构体似乎更像是一种如何使用数据的语法指示,但我宁愿只创建一个类,并尝试在类的名称中显式地表示它,或通过注释。
E.g.
class PublicInputData {
//data members
};
其他回答
c++中类和结构的区别是:
结构成员和基类/结构在默认情况下是公共的。 默认情况下,类成员和基类/结构是私有的。
类和结构都可以混合使用public、protected和private成员,可以使用继承,也可以有成员函数。
我向你推荐:
对于没有任何类样特性的普通旧数据结构使用struct; 在使用私有或受保护成员、非默认构造函数和操作符等特性时使用类。
正如每个人所说,唯一真正的区别是默认访问。但是,当我不想对简单的数据类进行任何形式的封装时,即使实现了一些helper方法,我也会特别使用struct。例如,当我需要这样的东西时:
struct myvec {
int x;
int y;
int z;
int length() {return x+y+z;}
};
摘自c++ FAQ Lite:
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 在c++中什么时候使用类?
我在定义函子和POD时使用struct。否则我就用class。
// '()' is public by default!
struct mycompare : public std::binary_function<int, int, bool>
{
bool operator()(int first, int second)
{ return first < second; }
};
class mycompare : public std::binary_function<int, int, bool>
{
public:
bool operator()(int first, int second)
{ return first < second; }
};
它们是一样的,只是默认值不同(class默认为private, struct默认为public),所以理论上它们是完全可以互换的。
所以,如果我只是想打包一些信息来移动,我使用一个结构体,即使我在那里放了一些方法(但不是很多)。如果它是一个最不透明的东西,其中主要使用将通过方法,而不是直接到数据成员,我使用一个完整的类。