使用基类类型指针指向派生类型对象

时间:2021-04-06 23:14:06

标签: c++ inheritance polymorphism

假设我们有以下代码:

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();

它是否只在我们想要访问基类的字段和属性时使用,但对于虚函数使用派生类的覆盖的?

1 个答案:

答案 0 :(得分:3)

在您的特定代码中,与第二种方法相比,使用第一种方法没有真正的好处。但是,请考虑当您有两个(或更多)派生类并希望使用指向其中一个类的实例的公共指针时,实际类型取决于某些(运行时)条件。这就是这种多态性显示其有用性的时候。

类似于以下内容:

int main()
{
    Base* b;
    std::cout << "Enter 1 or 2: ";
    int choice;
    std::cin >> choice;
    switch (choice) {
        case 1:
            b = new Derived1();
            break;
        case 2:
            b = new Derived2();
            break;
        default:
            b = new Base();
            break;
    }
    b->print();

    // ... other stuff to do with your polymorphic instance ...

    delete b; // ... and don't forget to delete it when you're done!
    return 0;
}

我将把它作为“读者练习”来提供 Derived1Derived2 类的定义。