我正在试验继承,并且遇到了特定的行为。首先,看代码:参数初始化列表中第二级类的构造函数的用途
class animal
{
public:
int ID;
animal(int id) : ID(id)
{
cout<<"I am an animal and I am not a terrorist. Here is my ID: "
<<ID<<endl;
}
};
class lion : virtual public animal
{
public:
lion(int id) : animal(id)
{
cout<<"I am a lion and I am not a terrorist. Here is my ID: "
<<ID<<endl;
}
};
class tiger : virtual public animal
{
public:
tiger(int id) : animal(id)
{
cout<<"I am a tiger and I am not a terrorist. Here is my ID: "
<<ID<<endl;
}
};
class liger : public lion, public tiger
{
public:
liger(int id) : lion(id), tiger(id), animal(id)
{
cout<<"I am a liger and I am not a terrorist. Here is my ID: "
<<ID<<endl;
}
};
在狮虎的构造为liger(int id) : lion(id), tiger(id), animal(id)...
和我创造了像liger l(444)
然后一个对象,我得到了以下的预期输出:
I am an animal and I am not a terrorist. Here is my ID: 444
I am a lion and I am not a terrorist. Here is my ID: 444
I am a tiger and I am not a terrorist. Here is my ID: 444
I am a liger and I am not a terrorist. Here is my ID: 444
然后,我把它改成以liger(int id) : lion(55), tiger(55), animal(id)
但它也给出了相同的输出。 现在,我的问题是,如果忽略lion
和tiger
构造函数的参数,那么它们的目的是什么?
当您使用虚拟继承时,基类的构造函数仅被调用一次是最派生的类。 – Jarod42 2014-10-03 12:04:12
[**请参阅此问题**](http://stackoverflow.com/questions/6461784/understanding-virtual-base-classes-and-constructor-calls)。然后,1.您的代码中有多少位置是您设置的** ID? 2.你的*输出中有多少个地方*你看到该函数被调用? 3.你为什么这样认为? (答:研究虚拟基类构造函数何时/如何在类似于你的层次结构中被解雇。 – WhozCraig 2014-10-03 12:09:54