虚拟基类的初始化
无论虚拟基类出现在继承层次中的哪个位置上,它们都是在非虚拟基类之前被构造
虚拟基类的初始化成了最末层继承类的责
{
class Base {
public:
Base(){cout << "Base()\n";};
Base( string ){
cout << "Base(string)\n";
};
Base( const Base&){
cout << "Base(const Base&)\n";
};
// ...
protected:
string _name;
};
class Derived1 : /*virtual */public Base
{
public:
Derived1(){cout << "Derived1() : Base()\n";}
Derived1(string s) : Base(s){cout << "Derived1(string) : Base(string)\n";}
Derived1(const Derived1& d) : Base(d){cout << "Derived1(Derived) : Base(Base)\n";}
};
//
// class Derived2 : virtual public Base
// {
// public:
// Derived2(){cout << "Derived2() : Base()\n";};
// Derived2(string s) : Base(s){cout << "Derived2(string) : Base(string)\n";}
// Derived2(const Derived1& d) : Base(d){cout << "Derived2(Derived) : Base(Base)\n";}
// };
class VMI : public Derived1/*, public Derived2*/
{
public:
VMI(){cout << "VMI()\n";}
//如果初始化列表中没有Base(s)则Base用默认构造函数构造
VMI(string s) : Derived1(s)/*, Derived2(s),*//*Base(s)*/{
cout << "VMI(string)\n";
}
VMI(const VMI& v) : /*Derived2(v), */Derived1(v)/*,Base(v)*/{
cout << "VMI(const VMI &)\n";
}
};
class Final : public VMI
{
public:
Final(){cout << "Final()\n";}
//如果初始化列表中没有Base(s)则Base用默认构造函数构造
Final(string s) : VMI(s)/*, Base(s)*/{
cout << "Final(string) \n";
}
Final(const Final& f): VMI(f)/*,Base(f)*/{
cout << "Final(const Final&)\n";
}
};
inline void test()
{
Final f;
cout << endl;
Final s("s");
cout << endl;
Final c(f);
}
}