C++学习笔记——多继承机制下构造函数的调用顺序(2)

       如果派生类有一个虚基类作为祖先类,那么在派生类构造函数的初始化列表中需要对虚基类构造函数的调用,如果未列出则表明用的是虚基类的无参数构造函数。
       不管初始化列表中次序如何,对虚基类构造函数的调用总是先于先于普通基类的构造函数。
       虚基类的唯一副本只被初始化一次。
举个例子:
基类:
class Base1
{
public:
	Base1() { cout << "Constructing Base1" << endl; }
};
class Base2
class Base2
{
public:
	Base2() { cout << "Constructing Base2" << endl; }
};
派生类:
class Derived1 :public Base2, virtual public Base1
{
public:
	Derived1() { cout << "Constructing Derived1 " << endl; }
};
class Derived2 :public Base2, virtual public Base1
{
public:
	Derived2() { cout << "Constructing Derived2" << endl; }
};
class Derived3 :public Derived1, virtual public Derived2
{
public:
	Derived3() { cout << "Constructing Derived3" << endl; }
};
主函数:
int main()
{
	Derived3 obj;
	return 0;
}
代码分析:
       1、关系图:

关系图

       2、思路整理

       根据前文,程序初始化时,先执行虚基类,Derived2 => Derived1 => Derived3;
              Derived2中,先执行虚基类,Base1 => Base2 => Derived2;
              Derived1中,先执行虚基类,Base1 => Base2 => Derived1;
              最后执行Derived3,结束。
       这样对吗?不对。因为Base1作为虚基类被初始化了两次!!!

运行结果:
Constructing Base1
Constructing Base2
Constructing Derived2
Constructing Base2
Constructing Derived1
Constructing Derived3
发布了27 篇原创文章 · 获赞 1 · 访问量 996

猜你喜欢

转载自blog.csdn.net/qq_41320782/article/details/104239472