zoukankan      html  css  js  c++  java
  • C++对象模型4--有重写的单继承

    有重写的单继承

    派生类中重写了基类的print()函数。

    //Derived_Overwrite.h
    #pragma once
    #include "base.h"
    
    class Derived_Overrite : public Base
    {
    public:
        Derived_Overrite(int);
        virtual ~Derived_Overrite(void);
        virtual void print(void) const;
     
    protected:
        int iDerived;
    };
    

      

    //Derived_Overwrite.cpp
    
    #include "stdafx.h"
    #include "Derived_Overwrite.h"
    
    
    Derived_Overrite::Derived_Overrite(int i):Base(0)
    {
    	iDerived = i;
    	cout<<"Derived_Overwrite::Derived_Overwrite()"<<endl;
    }
    
    Derived_Overrite::~Derived_Overrite(void)
    {
    	cout<<"Derived_Overwrite::~Derived_Overwrite()"<<endl;
    }
    
    void Derived_Overrite::print(void) const
    {
    	cout<<"Derived_Overwrite::print(), iDerived " << iDerived << endl;
    }
    

      BaseDerived_Overwrite的类图如下所示:

    clip_image018[3]

    重写print()函数在虚函数表中表现如下:

    clip_image020[3]

    为了验证上述C++对象模型,我们编写如下测试代码。

    void test_single_inherit_rewrite()
    {
    	Derived_Overwrite d(11111);
    	cout << "对象d的起始内存地址:" << &d << endl;
    	cout << "虚函数表地址:" << (int*)(&d) << endl;
    
    	//虚函数信息
    	cout << "虚函数表中第1个函数占位符的地址:" << (int*)*(int*)(&d) << "即析构函数在虚函数表中占位符的地址" << endl;
    	cout << "虚函数表中第2个函数占位符的地址:" << ((int*)*(int*)(&d) + 1) << endl;
    
    	typedef void(*Fun)(void);
    	Fun pFun = (Fun)*((int*)*(int*)(&d) + 1);
    	pFun();
    	d.print();
    	cout << endl;
    
    	cout << "虚函数表中第3个函数占位符的内容:" << *((int*)*(int*)(&d) + 2) << endl;
    	cout << endl;
    
    
    	cout << "推测数据成员iBase地址:" << ((int*)(&d) +1) << "通过地址取得的值:" << *((int*)(&d) +1) << endl;
        cout << "推测数据成员iDerived地址:" << ((int*)(&d) +2) << "通过地址取得的值:" << *((int*)(&d) +2) << endl;
    }
    

      代码执行结果:

    特别注意下,前面的模型虚函数表中最后一项没有打印出来,本实例中共2个虚函数,打印虚函数表第3项为0其实虚函数表以0x0000000结束,类似字符串以’’结束

  • 相关阅读:
    flask-bootstrap
    SSH
    Spring ContextLoaderListener与DispatcherServlet所加载的applicationContext的区别
    加载spring 的方法。
    简约的form表单校验插件
    javascript 大数值数据运算
    【解题报告】 Task
    【解题报告】 POJ1050 To the Max
    。。。
    【解题报告】 POJ2054 给树染色
  • 原文地址:https://www.cnblogs.com/stemon/p/4672936.html
Copyright © 2011-2022 走看看