使用子类的 ctor 进行初始化
Initializing with a subclass's ctor
struct A {
B b;
A(int x):b(x){}
A(int x, float g) // how to implement this? I want to init b as a C.
};
struct B {
enum {e_c, e_d} type;
int i;
B(int i_):i(i_){}
};
struct C : public B {
float f;
C(int i_, float f_):B(i),f(f_){}
};
struct D : public B {
double ff;
D(int i_, double d):B(i),ff(d){}
};
也许有另一种方法来编码这个?最初我只拥有类B,但我决定将其拆分,因此我没有继续向B添加(不兼容/互斥)字段。我的解决方案是,当A使用B时,它会检查B的enum以查看它是什么类型,然后将B*转换为C*或D*以获得float或double。我现在的问题是,我不知道如何让A初始化b,语言允许我这样做吗?
edit:我刚刚意识到A的b不可能分配空间来允许C或D的额外字段。没有任何可用空间来存储浮点数或双精度数。所以我想正确的方法是在B中加入union {float f; double ff;};
?
你的例子有点混乱。但也许你想要一个指针?
struct A {
B *b;
A(int x):b(new B(x)) {}
A(int x, float g):b(new C(x,g)) {}
~A() { delete b; } // Very important!
};
注意,如果这样做,B
必须有虚析构函数。您还需要考虑复制A
对象意味着什么。
你的编辑是正确的。
可能您想要的正常方法是通过(最好是智能)指针存储B
并在各自的构造函数中分配适当的类型。
相关文章:
- 模板 ctor 类型推导不起作用(没有匹配的构造函数用于初始化 ...)与函数<>参数
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 为什么部分初始化一个类然后调用委托 ctor 失败?
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 使用非默认 Ctor 初始化类类成员
- GCC缺少优化CTOR初始化器列表的机会
- 如果明确默认的constexpr ctor允许非constexpr初始化
- 是否可以使用 lambda 初始化变量(删除复制 ctor 时)
- 如何使用运行时选择基 CTOR 初始化不可复制的基类
- 我实际上是在调用 ctor 并在指向对象的指针上初始化 vtable 吗?C++
- 在 ctor 中使用 const&vector 初始化的 const&vector 成员
- 使用大括号初始化列表或传统的 ctor 语法实例化类型
- 在C++中定义构造器的更好方法是什么?初始化列表或 Ctor 正文中的初始化
- 复制列表初始化是否在概念上调用复制 ctor
- 初始化ctor中的随机常数值
- 正在初始化可移动类的ctor中的std::thread
- 在 ctor 的初始化列表中使用算术是否稳定?
- std::atomic::无法在 ctor 初始化列表中调用存储
- 使用子类的 ctor 进行初始化
- 数组对象初始化,其类具有某种ctor/dtor