如何强制转换,并在运行时CPP创建对象?

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

我想首先创建一个父类的对象,并根据一些条件创建子类的子对象并将它放入父对象。现在,在经过对象的一些函数功能后,需要获得访问子类的方法。请参阅澄清的代码。

class Parent {
    virtual f(){
        print('Parent');
    }
}

class Child: public Parent{
    virtual f(){
        print('Child')
    }
}

void do_something(Parent &obj){
    obj.f(); // this will print Child
}

int main(){

    Parent obj;
    if(cond){
        // This is my actual question
        // Not sure how to create a child obj here and put it into parent obj
        Child obj = dynamic_cast<Child>(obj);
    }   

    do_something(obj) // pass the child obj
}
c++ inheritance dynamic-cast
1个回答
2
投票
  1. 使用指针,而不是一个对象。 Parent* ptr = nullptr; if(cond){ ptr = new Child(); } if ( ptr ) { do_something(*ptr) // pass the child obj }
  2. 更改do_something使用参考,而不是一个对象。当参数是由该对象的值传递,程序从objct-slicing problem受损。 void do_something(Parent& obj){ .... }
  3. 更改do_something调用f()传递的对象上。 void do_something(Parent& obj){ obj.f(); }
© www.soinside.com 2019 - 2024. All rights reserved.