zoukankan      html  css  js  c++  java
  • C++该typeid和dynamic_cast

    1、typeid在没有虚拟函数的(不相关的动态绑定),typeid它只返回操作对象的实际类型

    2、typeid涉及到动态联编问题时(使用基类指针p或者引用p操作派生类对象),typeid(p)返回基类类型,typeid(*p)返回派生类类型;typeud(&p)返回基类类型。typeid(p)返回派生类类型

    3、dynamic_cast在动态联编(实时类型信息)问题中,能够实现基类指针(或引用)和派生类指针(或引用)之间的尝试性动态转换


    #include "stdafx.h"
    #include <iostream>
    #include <typeinfo>
    using namespace std;
    
    class Base
    {
    public:
    	int m_base;
    	virtual void show()
    	{
    		cout<<"This is Base class"<<endl;
    	}
    };
    class Derived:public Base
    {
    public:
    	int m_derived;
    	void show()
    	{
    		cout<<"This is Derived class"<<endl;
    	}
    };
    
    int main(int argc,char* argv[])
    {
    	Base *pb=new Derived();
    
    	cout<<typeid(pb).name()<<endl;
    	cout<<typeid(*pb).name()<<endl;
    
    	system("pause");
    	return 0;
    }


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    第七周课程总结&实验报告(五)
    2020软件工程作业02
    自我介绍
    2019学期总结
    2019 第二次实验报告
    git 小错误
    12
    2019第十一周作业
    第十周作业
    第九周
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4625348.html
Copyright © 2011-2022 走看看