菱形繼承與虛基類

FigureOut發表於2024-03-31

菱形繼承會存在多份資料的問題,使用虛繼承解決問題

虛基類指標vbptr

#include <iostream>

class Animal{
    public :
    int m_Age;
};

class Sheep:virtual public Animal{
    public:
    Sheep(){
        std::cout<<"sheep"<<std::endl;
    };
    
};

class Tuo:virtual public Animal{
    public:
    Tuo(){
        std::cout<<"tuo"<<std::endl;
    };
};

class SheepTuo:public Sheep,public Tuo{
    public:
    SheepTuo(){
        std::cout<<"SheepTuo"<<std::endl;
    }
};

void test01(){
    SheepTuo sheeptuo;
    std::cout<<sheeptuo.Sheep::m_Age<<std::endl;
    std::cout<<sheeptuo.m_Age<<std::endl;
}

int main(){
    return 0;
}

  

相關文章