在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
我唯一一次使用结构体而不是类是在函数调用中使用函数子之前声明函数子,为了清晰起见,我想尽量减少语法。例如:
struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare());
其他回答
摘自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.
回答我自己的问题(无耻地),正如已经提到的,访问权限是c++中它们之间的唯一区别。
我倾向于仅将结构体用于数据存储。我将允许它获得一些帮助函数,如果它使处理数据更容易的话。然而,一旦数据需要流控制(即维护或保护内部状态的getter /setter)或开始获得任何主要功能(基本上更像对象),它将被“升级”为一个类,以更好地传达意图。
当我需要创建POD类型或函子时,我使用结构体。
它们几乎是一样的。由于c++的魔力,结构体可以像类一样保存函数、使用继承、使用“new”创建等等
唯一的功能区别是类以私有访问权限开始,而结构以public开始。这是对C语言的向后兼容。
在实践中,我总是使用结构体作为数据持有者,类作为对象。
什么时候你会选择使用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; }
};