msr*_*rd0 3 c++ oop inheritance subclass
我有以下代码(简化):
#include <cstdio>
class parent
{
public:
virtual void do_something() const
{
printf("hello I'm the parent class\n");
}
};
class child : public parent
{
public:
virtual void do_something() const
{
printf("hello I'm the child class\n");
}
};
void handle(parent p)
{
p.do_something();
}
int main()
{
child c;
handle(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这打印hello I'm the parent class,即使我传递了类型的参数child.我怎样才能告诉C++像Java那样行事并调用子方法,打印hello I'm the child class?
通过引用接受参数(或者,可能是const引用):
void handle (parent & p)
// note this ^
{
p.do_something();
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,切片发生:获取的parent部分child作为单独的类型对象提取parent并转到函数.
如果要将不同的子类放入单个集合中,通常的解决方案是使用智能指针,例如std::unique_ptr或std::shared_ptr.