首页 > 编程语言 > 详细

C++中深入理解dynamic_cast

时间:2019-10-23 21:48:11      阅读:65      评论:0      收藏:0      [点我收藏+]

转载:https://blog.csdn.net/gaojing303504/article/details/78860773

dynamic_cast运算符的主要用途:将基类的指针或引用安全地转换成派生类的指针或引用,

并用派生类的指针或引用调用非虚函数。如果是基类指针或引用调用的是虚函数无需转换就能在运行时调用派生类的虚函数。

前提条件:当我们将dynamic_cast用于某种类型的指针或引用时,只有该类型至少含有虚函数时(最简单是基类析构函数为虚函数),才能进行这种转换。否则,编译器会报错。

 

用个例子来说明:

1.基类中没有虚函数:

#ifndef _CLASS_H_
#define _CLASS_H_

class Base
{
public:
    Base();
    ~Base();
    void print();
};


class Inherit :public Base
{
public:
    Inherit();
    ~Inherit();

    void show();
};

#endif

 

#include "Class.h"
#include <iostream>
Base::Base()
{

}

Base::~Base()
{

}

void Base::print()
{
    std::cout << "Base funtion" << std::endl;
}

Inherit::Inherit()
{

}

Inherit::~Inherit()
{

}

void Inherit::show()
{
    std::cout << "Inherit funtion" << std::endl;
}
#include "Class.h"

int main()
{
    Base* pbase = new Inherit();

    Inherit* pInherit = dynamic_cast<Inherit*>(pbase);

    return 0;
}

编译器报错:

技术分享图片

 

 

我们改基类

class Base
{
public:
    Base();
    virtual ~Base();
    void print();
};
#include "Class.h"

int main()
{
    Base* pbase = new Inherit();

    Inherit* pInherit = dynamic_cast<Inherit*>(pbase);

    pInherit->show();//这样动态转换,我们就可以调用派生类的函数了

    return 0;
}

技术分享图片

 

C++中深入理解dynamic_cast

原文:https://www.cnblogs.com/chechen/p/11728743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!