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


当前回答

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++ 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 test_one {
    int main_one();
};

等于

class test_one {
  private:
    int main_one();
};

所以如果你尝试

int two = one.main_one();

我们将得到一个错误:main_one是私有的,因为它不可访问。我们可以 通过指定它的公共ie来初始化它来解决它

class test_one {
  public:
    int main_one();
};

结构体。

struct是一个类,其成员默认为public。

struct test_one {
    int main_one;
};

意味着main_one是私有的,即

class test_one {
  public:
    int main_one;
};

我用struct表示数据结构,其中成员可以取任何值 那样容易些。

我唯一一次使用结构体而不是类是在函数调用中使用函数子之前声明函数子,为了清晰起见,我想尽量减少语法。例如:

struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare()); 

什么时候你会选择使用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; }
};

我从来不在c++中使用struct。

我无法想象在需要私有成员时使用结构体的场景,除非您故意试图混淆。

使用结构体似乎更像是一种如何使用数据的语法指示,但我宁愿只创建一个类,并尝试在类的名称中显式地表示它,或通过注释。

E.g.

class PublicInputData {
    //data members
 };