使用子类的 ctor 进行初始化

Initializing with a subclass's ctor

本文关键字:初始化 ctor 子类      更新时间:2023-10-16
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并在各自的构造函数中分配适当的类型。