C++中深刻理解dynamic_cast

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

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

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

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

 

用个例子来讲明:.net

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;
}

编译器报错:code

 

 

咱们改基类blog

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;
}

相关文章
相关标签/搜索