C++虚继承初始化顺序

穿精又带淫゛_ 提交于 2020-03-25 17:07:39

3 月,跳不动了?>>>

  1. 没有虚继承则从左往右

    	public D:public A,public B,public C{};
    	public D:public A,public C,public B{};
    
  2. 有虚继承则先构造虚继承的类然后再从左往右(如果某个普通类中有虚表,也要先虚继承构造)

    毕竟要避免菱形集成,就怕普通集成中有同一个基类。先构建虚表。

    	#include<iostream>
    	class INT
    	{
    	public:
    		int a;
    		INT(int ca=1):a(ca){std::cout<<"cint"<<a<<std::endl;}
    		operator int(){return a;}
    		int operator =(int ca ){a = ca;return a;}
    	};
    
    	class Test
    	{
    	public:
    		Test(){std::cout<<"test"<<std::endl;}
    	};
    
    	class A
    	{
    	public:
    		INT a;
    		A(int aa=12):a(aa){a=aa;std::cout<<"ca"<<a<<std::endl;}
    	};
    	class B:public virtual A{
    	public:
    		B(int b=1):A(b){a=b;std::cout<<"cb"<<a<<std::endl;}
    	};
    	class C:public virtual A{
    	public:
    		C(int c=11):A(c){a=c;std::cout<<"cc"<<a<<std::endl;}
    		// int c;
    	};
    
    	class D:public virtual A{
    	public:
    		D(int dd=12):A(dd){std::cout<<"cd"<<std::endl;}
    	};
    
    	class E:public virtual A{
    	public:
    		E(int dd=12):A(dd){std::cout<<"cE"<<std::endl;}
    	};
    
    	class Z:public Test,public D,public C,public E{
    	};
    
    	int main()
    	{
    		Z z;
    		return 0;
    	}
    
    	/*
    	cint12
    	ca12
    	test
    	cd
    	cc11
    	cE
    	[Finished in 5.2s]
    	*/
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!