【发布时间】:2021-07-02 18:25:41
【问题描述】:
假设我们有以下代码:
class Base
{
public:
virtual void print()
{
cout << "I'm base" << endl;
}
};
class Derived : public Base
{
public:
void print() override
{
cout << "I'm derived" << endl;
}
};
int main()
{
Base* b = new Derived();
b->print();
}
我无法理解的是:以这种方式而不是简单地创建对象有什么好处:
Derived* d = new Derived();
是否只在我们想要访问基类的字段和属性时使用,而对于虚函数使用派生类中的覆盖?
【问题讨论】:
标签: c++ inheritance polymorphism