多重继承

来源:互联网 发布:cmd查询数据库 编辑:程序博客网 时间:2024/05/16 16:17

https://www.oschina.net/translate/cpp-virtual-inheritance

可通过以下代码验证:

#include<iostream>using namespace std;/*class Top{     public:         int a;};class Left : public Top{     public:         int b;};class Right : public Top{     public:         int c;};class Bottom : public Left, public Right{     public:         int d;};int main(){    Bottom* bottom = new Bottom();    Left* left = bottom;    Right* right = bottom;    //Top* top = bottom;    //出现二义性(ambiguous)    Top* topL = (Left*) bottom;    Top* topR = (Right*) bottom;    topL->a = 1;    topR->a = 2;    //cout<< bottom->a <<endl;  //二义性    cout<< sizeof(*bottom) <<endl;  //结果为20(包含两个a,一个b一个c一个d)    return 0;}*/class Top{     public:         int a;};class Left : virtual public Top{     public:         int b;};class Right : virtual public Top{     public:         int c;};class Bottom : public Left, public Right{     public:         int d;};int main(){    Bottom* bottom = new Bottom();    Left* left = bottom;    Right* right = bottom;    Top* top = bottom;  //不会有二义性    Top* topL = (Left*) bottom;    Top* topR = (Right*) bottom;    topL->a = 1;    topR->a = 2;    cout<< bottom->a <<endl;    //不会有二义性    //类的每个虚拟基类都有一个vptr指针    //虽然bottom中公用一个Top对象,但是bottom中添加了vptr.Left    //和vptr.Right两个指针,这两个指针都指向了Top    cout<< sizeof(*bottom) <<endl;  //结果为24    return 0;}
0 0
原创粉丝点击