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 的枚举以查看它是什么类型,然后将 B* 转换为 C* 或 D* 以获得 float 或 double 。我现在的问题是我不知道如何让A 初始化b。这种语言甚至允许我做那样的事情吗?
编辑:我刚刚意识到 A 的 b 不可能分配空间来允许 C 或 D 的额外字段。不会有任何可用空间来存储 float 或 double 。所以我想做我想做的事情的正确方法是在 B 中添加一个 union {float f;双 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
对象意味着什么。
关于c++ - 使用子类的构造函数进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6604136/