基类类型向量中的派生结构

Derived structs in base class-type vectors

本文关键字:派生 结构 类型 向量 基类      更新时间:2023-10-16

我有一个工厂,它创建的结构都是从基结构派生的,这些结构都有某些成员的默认值。当我将对象添加到基类型的指针向量时,它似乎重置为基成员数据。该对象仍然完好无损,我可以访问派生成员,但是从容器引用时,类型具有基值。

struct a {
unsigned int type = 0;
};
struct b : a {
unsigned int type = 1;
};

std::vector<a *> container;
b * message = new b;
container.push_back(message);

消息>类型为 1

容器[0]->类型为 0

当我推入矢量时,我尝试过以不同的方式进行投射,但无济于事

这段代码实际上做了什么:

struct a {
unsigned int type = 0;
};
struct b : a {
unsigned int type = 1;
};

是不是b有两个type成员,即a::typeb::type,一个隐藏另一个。成员变量不能以与成员函数相同的意义重写或virtual。当你通过指向a的指针访问message(其类型为b(时,编译器只能看到a::type,导致你观察到的结果。有关重写成员变量的更多讨论,请参阅此处。如果设计仅限于单个type成员,则可以进行以下简单更改:

struct a {
a(unsigned int _type = 0) : type(_type) {} // default constructor initializes type to 0
unsigned int type;
};
struct b : a {
b() : a(1) {} // default constructor initializes inherited type to 1
// no ambiguous 'type' member here
};

但是,如果您需要根据任意子类型执行复杂的逻辑,则最好开始了解virtual成员函数