我有三种类类型:Base->Center->Child,我想让从父类型构造子类型成为可能,所以我这样声明它们:
class Base {
public:
Base(void) {cout << "Base()" << endl;}
virtual ~Base(void) {}
Base(const Base &ref) {cout << "Base(const Base &)" << endl;}
};
class Center : public virtual Base {
public:
Center(void) : Base() {cout << "Center()" << endl;}
Center(const Base &ref) : Base(ref) {cout << "Center(const Base &)" << endl;}
};
class Child : public virtual Center {
public:
Child(void) : Center() {cout << "Child()" << endl;}
Child(const Base &ref) : Center(ref) {cout << "Child(const Base &)" << endl;}
};
可以这样调用:(调用Center和Base的拷贝构造函数)
Base base;
Center center(base);
.
但是,这些代码的行为出乎意料:
Child child(base);
输出是:
Base()
Center(const Base &)
Child(const Base &)
为什么叫 Base(void) 而不是 Base(const Base &)?
解决了(非常感谢 Dietmar Kühl 和 Adam Burry)
两种方法:
1. add Base(const Base &) to Child, which would looks like this:
Child(const Base &ref) : Base(ref), Center(ref) {}
2. or, remove virtual inheritance, which would looks like this:
class Center : public Base {...}
class Child : public Center {...}