我想首先创建一个父类的对象,然后根据某种条件创建子类的子对象并将其放入父对象。现在,在将对象传递给某个函数之后,该函数需要访问子类方法。请查看代码以进行澄清。
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
}
答案 0 :(得分:2)
使用指针代替对象。
Parent* ptr = nullptr;
if(cond){
ptr = new Child();
}
if ( ptr )
{
do_something(*ptr) // pass the child obj
}
更改do_something
以使用引用,而不是对象。当参数按对象的值传递时,程序将遭受objct-slicing problem的困扰。
void do_something(Parent& obj){
....
}
更改do_something
以在传递的对象上调用f()
。
void do_something(Parent& obj){
obj.f();
}