在不使用dynamic_cast的情况下将基类对象指针转换为派生类对象指针

时间:2019-10-18 06:24:29

标签: c++ rtti

由于性能问题,不允许我使用dynamic_castvirtual function。现在,我需要从传递给函数的父类指针中获取子对象。关于它指向哪个子对象的信息不可用。如果允许使用动态投射,它将解决此问题。

作为一种解决方法,我目前正在基类中存储一个包含有关子对象的类型信息的枚举。收到基类指针后,我将获取指向的派生类对象的类型以形成存储在枚举中的值,然后对它进行static_cast
我知道这不是一个适当的解决方案。有没有可能失败的情况?还有其他解决方案吗?


#include <iostream>

using namespace std;
enum class Type{
    Derived1,
    Derived2
};

class Base{
    public:
    Type type;
    Base(){};
    Base(Type t){type = t;}
    void print(){cout<<"in Base"<<endl;}
};

class Derived1: public Base{
    public:
    Derived1():Base(Type::Derived1){}
    void print(){cout<<"in Derived1"<<endl;}
    void run(){cout<<"in Derived1"<<endl;}
};

class Derived2: public Base{
    public:
    Derived2():Base(Type::Derived2){}
    void print(){cout<<"in Derived2"<<endl;}
    void run(){cout<<"in Derived2"<<endl;}
};

int main()
{
    Base* a = new Derived1();
    Derived1* b;
    if(a->type == Type::Derived1){
        b= static_cast<Derived1*>(a);
    }
    b->print();  \\in Derived2
    b->run();    \\in Derived2
    return 0;
}

0 个答案:

没有答案