如何在cpp中的运行时中进行类型转换和创建对象?

时间:2019-02-05 23:25:28

标签: c++ inheritance dynamic-cast

我想首先创建一个父类的对象,然后根据某种条件创建子类的子对象并将其放入父对象。现在,在将对象传递给某个函数之后,该函数需要访问子类方法。请查看代码以进行澄清。

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
}

1 个答案:

答案 0 :(得分: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();
    }