在c++中,在哪些情况下使用结构体比使用类更好?


当前回答

回答我自己的问题(无耻地),正如已经提到的,访问权限是c++中它们之间的唯一区别。

我倾向于仅将结构体用于数据存储。我将允许它获得一些帮助函数,如果它使处理数据更容易的话。然而,一旦数据需要流控制(即维护或保护内部状态的getter /setter)或开始获得任何主要功能(基本上更像对象),它将被“升级”为一个类,以更好地传达意图。

其他回答

struct对我有帮助的一个地方是,当我有一个系统从另一个系统接收固定格式的消息(通过串行端口)时。您可以将字节流转换为定义字段的结构,然后轻松访问这些字段。

typedef struct
{
    int messageId;
    int messageCounter;
    int messageData;
} tMessageType;

void processMessage(unsigned char *rawMessage)
{
    tMessageType *messageFields = (tMessageType *)rawMessage;
    printf("MessageId is %d\n", messageFields->messageId);
}

显然,这与您在C中所做的事情相同,但我发现必须将消息解码为类的开销通常是不值得的。

我只在需要保存一些没有任何成员函数与之关联的数据(对成员数据进行操作)并直接访问数据变量时使用struct。

从文件和套接字流等读取/写入数据。在函数参数太多且函数语法看起来太冗长的结构中传递函数参数。

从技术上讲,类和结构之间没有太大的区别,除了默认的可访问性。 更重要的是,它取决于你如何使用它的编程风格。

对于c++来说,结构体和类之间并没有太大的区别。主要的功能区别是,结构的成员在默认情况下是公共的,而在类中默认情况下是私有的。否则,就语言而言,它们是等价的。

也就是说,我倾向于在c++中使用结构体,就像我在c#中做的那样,类似于Brian所说的。struct是简单的数据容器,而类用于对象,除了保存数据外,还需要对数据进行操作。

摘自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.

现有的答案中有很多误解。

class和struct都声明一个类。

是的,您可能必须在类定义中重新安排访问修改关键字,这取决于您用于声明类的关键字。

但是,除了语法之外,选择一种而不是另一种的唯一原因是惯例/风格/偏好。

有些人喜欢对没有成员函数的类坚持使用struct关键字,因为最终的定义“看起来像”C中的简单结构。

类似地,有些人喜欢对具有成员函数和私有数据的类使用class关键字,因为它表示“类”,因此看起来像他们最喜欢的面向对象编程书籍中的示例。

实际上,这完全取决于您和您的团队,这对您的程序没有任何影响。

下面这两个类除了名字以外在其他方面都是完全等价的:

struct Foo
{
   int x;
};

class Bar
{
public:
   int x;
};

你甚至可以在重新声明时切换关键字:

class Foo;
struct Bar;

(虽然这将破坏Visual Studio构建由于不一致,所以编译器将发出一个警告,当你这样做。)

下面的表达式都为true:

std::is_class<Foo>::value
std::is_class<Bar>::value

不过,请注意,在重新定义时不能切换关键字;这只是因为(根据单定义规则)跨翻译单元的重复类定义必须“由相同的标记序列组成”。这意味着你甚至不能交换const int成员;,并且与类或结构的语义无关。