联盟与结构中的继承

时间:2017-02-06 23:27:18

标签: c++ inheritance unions

假设我有一些结构,基本上有一个'一般'字段和一些独特的数据,如:

struct A
{
    char type;
    int data;
};

struct B
{
    char type;
    int data[2];
};

等等(我有很多)。所以我可以创建一个具有相同字段的基础结构,并继承其他字段。我虽然可以使用union做同样的事情,例如:

union AnyClass
{
    struct A _a;
    struct B _b;
    ...
};

我收到一些数据(完全适合union中最大的成员),所以我更喜欢使用以下语法:

// to read it from buffer (I am receiving data from another PC, which stores data the same way (in the same union) as I do
char buf[sizeof(AnyClass)];
char type = buf[0]; // detect type
AnyClass inst;
memcpy(&inst, buf, sizeof(inst));
switch(type)
{
    ... // handle data according to its type
}

// if I want to create a new object, and send it, I can use
AnyClass myObj;
new (&myObj._b) B();
... // do whatever I want

注意:我知道我必须以某种方式对齐数据,因此两台计算机(接收/发送方)都应正确解释buf。

  1. 使用BaseStructure运行得比同一问题解决方案更快,并继承其他问题(所以,我必须立即强制转换它们),否则它将编译成几乎相同的代码?
  2. 可以使用,还是设计不佳?
  3. 如果还有其他解决方案,您能否尽快解释一下?

1 个答案:

答案 0 :(得分:3)

上述方法之间的性能差异很小。这是一个很好的机会,你根本不会注意到它。

我会像你那样塑造你的课程:

class AnyClass
{
    char type;
    union
    {
        struct
        {
             int data1;
        };
        struct
        {
             int data2[2];
        };
    };

; 

请注意使用匿名结构和联合。

为什么你需要字符缓冲区?始终分配类型化结构,并在没有ctors和dectors的情况下更好地定义它。我不喜欢这句话:

char type = buf[0]; // detect type

这里你直接假设物理偏移量。关于结构布局的假设越少,结果就越好。

相关问题