• C++中深入理解dynamic_cast


    转载: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;
    }

  • 相关阅读:
    isequal 和startswith 使用
    UVa10340
    UVa1368
    UVa455
    UVa1225
    UVa1586
    UVa 1585
    UVa10082
    UVa272
    NYOJ1
  • 原文地址:https://www.cnblogs.com/chechen/p/11728743.html
Copyright © 2020-2023  润新知