开发者

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){}
};

Perhaps there is another way to code this? Originally I just had the class B, but I decided to split it up so I didn't keep adding (incompatible/mutually exclusive) fields to B. My solution was, when A uses b i开发者_如何学编程t checks b's enum to see what type it is, then casts a B* to a C* or a D* to get the float or double. My problem is now I don't know how to let A initialize b. Does the language even let me do something like that?

edit: I just realized A's b couldn't possibly have allocated space to allow for C or D's extra fields. There wouldn't be any available space to store the float or double. So I guess the right way to do what i want is to add into B a union {float f; double ff;};?


Your example is a bit confused. But maybe you want a pointer?

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!
};

Note that if you do this, B must have a virtual destructor. You will also need to think about what it means to copy an A object.


Your edit is correct.

Probably the normal way to do what you want is to store the B by (preferably smart) pointer and allocate the proper type in the respective constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜