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


当前回答

摘自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++实现提供兼容C的接口时,struct(更一般地说是PODs)非常方便,因为它们可以跨语言边界和链接器格式移植。

如果您不关心这一点,那么我认为使用“struct”而不是“class”是一种很好的意图交流方式(如上面的@ZeroSignal所述)。struct还具有更可预测的复制语义,因此对于打算写入外部媒体或通过网络发送的数据非常有用。

struct对于各种元编程任务也很方便,比如trait模板只暴露了一堆依赖的typedef:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...但这实际上只是利用了struct的默认保护级别是公共的……

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中所做的事情相同,但我发现必须将消息解码为类的开销通常是不值得的。

如果你写的库内部是c++,但API可以被C或c++代码调用,你可以在c++中使用"struct"。你只需要创建一个包含struct和全局API函数的头文件,就可以向C和c++代码公开,如下所示:

// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif

// Put your C struct's here
struct foo
{
    ...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;

// Put your C API functions here
void bar(foo *fun);

#ifdef __cpp
}
#endif

然后,您可以使用c++代码在c++文件中编写函数栏(),并使其可从C调用,两个世界可以通过声明的结构共享数据。当然,在混合使用C和c++时还有其他注意事项,但这是一个简化的示例。

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

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

默认情况下,结构具有公共访问权限,类具有私有访问权限。

就我个人而言,我使用结构作为数据传输对象或作为值对象。当这样使用时,我将所有成员声明为const,以防止其他代码修改。