zoukankan      html  css  js  c++  java
  • 菱形继承问题以及解决

    1.1     解决问题利用虚基类

    1.2     sheepTuo内部结构

    1.2.1     vbptr 虚基类指针

    1.2.2     指向一张 虚基类表

    1.2.3     通过表找到偏移量

    1.2.4     找到共有的数据

    #define _CRT_SECURE_NO_WARNINGS
    #include<iostream>
    using namespace std;
    
    class Animal
    {
    public:
    	int m_Age;
    };
    
    //虚基类 Sheep
    class Sheep :virtual public Animal
    {
    };
    //虚基类 Tuo
    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 << st.Sheep::m_Age << endl;
    	cout << st.Tuo::m_Age << endl;
    	cout << st.m_Age << endl; //可以直接访问,原因已经没有二义性的可能了,只有一份m_Age
    }
    
    //通过地址 找到 偏移量
    //内部工作原理
    void test02()
    {
    	SheepTuo st;
    	st.m_Age = 100;
    
    	//找到Sheep的偏移量操作
    	//cout<< *(int *)((int *)*(int *)&st + 1) << endl;
    
    	cout << *(int*)((int*)*(int *)&st + 1) << endl;
    
    	//找到Tuo的偏移量
    	cout << *((int *)((int *)*((int *)&st + 1) + 1)) << endl;
    	
    	//输出Age
    	cout << ((Animal*)((char *)&st + *(int*)((int*)*(int *)&st + 1)))->m_Age << endl;
    
    }
    
    int main(){
    
    	//test01();
    	test02();
    
    	system("pause");
    	return EXIT_SUCCESS;
    }
    

      

  • 相关阅读:
    IOS 作业项目(1) 关灯游戏 (百行代码搞定)
    Object-C 基础笔记5---Category
    Object -c基础知识(5)--release 之后 retainCount为何为1
    Foundation--NSString , array and Dictionary
    Foundation--结构体
    Object-C 基础笔记4---ARC内存管理
    141. Linked List Cycle
    139. Word Break
    138. Copy List with Random Pointer
    133. Clone Graph
  • 原文地址:https://www.cnblogs.com/Malphite/p/14465724.html
Copyright © 2011-2022 走看看