基类类型向量中的派生结构
Derived structs in base class-type vectors
我有一个工厂,它创建的结构都是从基结构派生的,这些结构都有某些成员的默认值。当我将对象添加到基类型的指针向量时,它似乎重置为基成员数据。该对象仍然完好无损,我可以访问派生成员,但是从容器引用时,类型具有基值。
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::type
和b::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
成员函数
相关文章:
- 初始化派生结构的基部分/意外打包派生结构字段以对齐基结构的间隙
- 有没有办法将C++结构/类中的所有定义都纳入范围而不从中派生?
- 受保护的嵌套结构不能用作派生外部类中的返回类型?
- 基类类型向量中的派生结构
- 使用 static_cast 更改派生结构成员
- C++ 在派生类中访问基的私有结构
- 为什么C++可以使用派生结构来实例化其父模板结构,而父模板可以调用子结构的函数?
- C 结构实现派生接口
- 从派生类重新定义基类中定义的结构
- 具有灵活大小的结构的 MPI 派生数据类型
- 是否可以将基类的结构分配给派生类的结构
- 如何在派生类中初始化继承的模板POD结构
- 是否可以在 c++ 中的派生类中以特定偏移量附加结构
- 在 c++ 的编译时初始化派生结构类型的变量
- Gcc /clang在基结构的后填充中布局派生结构的字段
- 具有模板化基类型的派生结构的结构初始化
- 使用memset对派生结构体进行归零
- 从基创建派生结构
- 派生结构与指向其他结构的结构
- c++将派生结构传递给期望超结构的方法