#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;//動物類
class Animal
{
public:int m_Age; //年齡
};//virtual加上后 繼承方式 數據虛繼承
// Animal類 變為 虛基類
//羊類
class Sheep : virtual public Animal
{};//駝
class Tuo : virtual public Animal
{};//羊駝
class SheepTuo : public Sheep, public Tuo
{};void test01()
{SheepTuo st;st.Sheep::m_Age = 10;st.Tuo::m_Age = 20;cout << "age = " << st.Sheep::m_Age << endl;cout << "age = " << st.Tuo::m_Age << endl;cout << "age = " << st.m_Age << endl;//m_Age只需要一份即可,菱形繼承導致數據有一份浪費}//虛繼承內部工作原理
void test02()
{SheepTuo st;st.m_Age = 100;//通過sheep找到偏移量值cout << "通過sheep找到的偏移量為:" << *(int *)((int*)*(int *)&st + 1) << endl;//通過Tuo找到偏移量值cout << "通過Tuo找到的偏移量為:" << *(int *)((int*)*((int *)&st + 1) + 1) << endl;//通過偏移量 求出m_Age的值cout << "age = " << ((Animal *)((char *)&st + (*(int *)((int*)*(int *)&st + 1))))->m_Age << endl;}int main(){//test01();test02();system("pause");return EXIT_SUCCESS;
}
ps: 這里注意指針 步長的概念, 不同的指針類型, 步長不一樣, 增加或減少的幅度不一樣, 切記!!!