【发布时间】:2016-04-26 17:24:18
【问题描述】:
我有以下代码(简化):
#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;
}
这会打印hello I'm the parent class,即使我传递了child 类型的参数。如何告诉 C++ 像 Java 一样运行并调用子方法,打印 hello I'm the child class?
【问题讨论】:
-
baseclass 是更常用的术语。
标签: c++ oop inheritance subclass