【发布时间】:2016-05-20 18:02:03
【问题描述】:
这是代码:
struct Biology
{
Biology() { cout << "Biology CTOR" << endl; }
};
struct Human : Biology
{
Human() { cout << "Human CTOR" << endl; }
};
struct Animal : virtual Biology
{
Animal() { cout << "Animal CTOR" << endl; }
};
struct Centaur : Human, Animal
{
Centaur() { cout << "Centaur CTOR" << endl; }
};
int main()
{
Centaur c;
return 0;
}
此代码打印:
Biology CTOR
Biology CTOR
Human CTOR
Animal CTOR
Centaur CTOR
为什么?
由于我们创建了一个Centaur 对象,我们从构建Centaur 开始,通过构造Human、Animal 和最后Centaur(我们从派生较少到派生最多)。
让我们从Human开始:
Human继承自Biology,所以我们先调用Biology的构造函数。
现在Human的基类已经构建好了,我们终于可以自己构造Human了。
但是,Biology 会再次构造!
为什么?幕后发生了什么?
请注意,这完全是故意让Animal 虚拟继承自Biology,同时,它也是故意让Human 非虚拟继承自Biology。
我们正在以不正确的方式解决可怕的钻石:人类和动物都应该实际上继承生物学来完成这项工作。
我只是好奇。
另外,请参阅此代码:
struct Biology
{
Biology() { cout << "Biology CTOR" << endl; }
};
struct Human : virtual Biology
{
Human() { cout << "Human CTOR" << endl; }
};
struct Animal : Biology
{
Animal() { cout << "Animal CTOR" << endl; }
};
struct Centaur : Human, Animal
{
Centaur() { cout << "Centaur CTOR" << endl; }
};
int main()
{
Centaur c;
return 0;
}
这里我们有Human 几乎继承自Biology,而Animal 设置为以“经典方式”继承。
但这一次,输出不同:
Biology CTOR
Human CTOR
Biology CTOR
Animal CTOR
Centaur CTOR
这是因为Centaur起初从Human继承,然后从Animal继承。
如果顺序相反,我们将获得与之前相同的结果,在第一个示例中 - 连续构造两个 Biology 实例。
这是什么逻辑?
请试着解释一下你的方式,我已经检查了很多关于这个的网站。但似乎没有一个能满足我的要求。
【问题讨论】:
-
多么好的问题!
标签: c++ inheritance constructor multiple-inheritance virtual-inheritance