【问题标题】:Usage of base class type pointer to the derived type object使用指向派生类型对象的基类类型指针
【发布时间】: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


    【解决方案1】:

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

    类似于以下内容:

    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 类的定义。

    【讨论】:

    • 别忘了给Base添加一个virtual析构函数,当你使用完对象之后再调用delete b;
    • @RemyLebeau 确实 - 另一个“读者练习”。
    • @RemyLebeau 是的,我只是想让示例尽可能简单,以指出我提出的具体问题。
    猜你喜欢
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多