((C ++))不应该此dynamic_cast检索派生类[duplicate]

问题描述 投票:0回答:1

阅读casts in C++之后,我了解到dynamic_cast应该在“丢失”时检索派生类。以下示例证明我错了。但我还是不明白:

尝试dynamic_cast(B * po = dynamic_cast(&ao);)会使编译失败,尽管老式的强制转换将使编译成功,并且运行将按预期进行。

//g++  5.4.0
#include <iostream>
using namespace std;

class A{
    protected:
    int x;
    A(int _x) : x(_x) {}
    public:
    A() : x(-1) {}
    void p() { cout << "(A) x = " << x << endl; };
    ~A(){ cout << "destroy A" << endl; }
};

class B : public A{
    public:
    B() : A(-2) {}
    void p() { cout << "(B) x = " << x << endl; };
};

A& f( A& o ) { return o; }

int main()
{
    cout << "start\n";
    {
        B o;
        A ao = f(o);
        ao.p();
        //B* po = dynamic_cast<B*>(&ao); //this fails with following error :
        // source_file.cpp:32:37: error: cannot dynamic_cast ‘& ao’ (of type ‘class A*’) to type ‘class B*’ (source type is not polymorphic)
        B* po = (B*)(&ao);
        po->p();
    }
    cout << "stop\n";
}

//trace
//
//start
//start
//(A) x = -2
//(B) x = -2
//destroy A
//destroy A
//stop
c++ dynamic-cast
1个回答
0
投票

为了使dynamic_cast<>工作,该对象需要具有一个vtable。否则,对象内没有指示它属于哪个动态类。

仅当该vtable包含至少一个虚函数时,该vtable才会添加到C ++类。

因此,请在类中至少添加一个虚函数,然后动态转换应该起作用。

© www.soinside.com 2019 - 2024. All rights reserved.