• dynamic_cast


    dynamic 转换时的类必须有虚函数,否则会编译报错。

    #include <iostream>
    using namespace std;
    
    
    class A
    {
    public:
        int a ;
        int b;
        void prt(void){std::cout <<"prt here" << std::endl;}
        //virtual ~A(){};
    };
    
    class B: public A
    {
    };
    
    class C: public A
    {
    };
    
    int main()
    {
        A *pA = new B;
        A& rA = *pA;
    
        B *pB = dynamic_cast<B*> (pA);
        cout <<"1
    ";
        cout <<pB<<endl;
        fflush(stdout);
        C& rC = dynamic_cast<C&> (rA);
        cout <<"2";
        fflush(stdout);
    }

    编译报错:

    > g++ main.cpp
    main.cpp: In function 'int main()':
    main.cpp:26: error: cannot dynamic_cast 'pA' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
    main.cpp:27: error: cannot dynamic_cast '(A&)((A*)rA)' (of type 'class A&') to type 'class C&' (source type is not polymorphic)
    > fg

    加上虚析构函数后,编译通过,运行结果,

    Suspended
    > ./a.out 
    1
    0x28301030
    terminate called after throwing an instance of 'std::bad_cast'
      what():  std::bad_cast
    Abort (core dumped)

    可见在第二个dynamic_cast 时抛出异常,原因是B类型无法转换成C类型。

    作用:将一个基类对象指针(或引用)cast到继承类指针,dynamic_cast会根据基类指针是否真正指向继承类指针来做相应处理, 
           即会作一定的判断。 
           对指针进行dynamic_cast,失败返回null,成功返回正常cast后的对象指针; 
           对引用进行dynamic_cast,失败抛出一个异常,成功返回正常cast后的对象引用。 
      
    注意:dynamic_cast在将父类cast到子类时,父类必须要有虚函数。例如在下面的代码中将CBasic类中的test函数不定义成 
           virtual时,编译器会报错:error C2683: dynamic_cast : “CBasic”不是多态类型 
      

  • 相关阅读:
    【题解】【神奇校内POIN模拟赛】小凯的疑惑
    【题解】【CF670C】cinema
    11 Remove Duplicates from Sorted Array II
    10 3SumClosest
    7 Container With Most Water
    8 String to Integer (atoi)
    9 3Sum
    6 Palindrome Number
    5 Zigzag Conversion
    4 Longest Palindromic Substring
  • 原文地址:https://www.cnblogs.com/diegodu/p/4235834.html
Copyright © 2020-2023  润新知