【问题标题】:Why does this call to `getNoise` use the base class implementation and not the subclass implementation?为什么对“getNoise”的调用使用基类实现而不是子类实现?
【发布时间】:2020-01-06 16:36:52
【问题描述】:

问题

我的理解是,我们可以通过在基类中创建 getNoise 虚拟,然后在任何子类中覆盖它来实现多态。然后通过一个指针向量,我们存储用于调用方法的基类的地址,例如下面的getNosie

谁能告诉我为什么我的代码不这样做?

代码

#include <iostream>
#include <vector>
#include <memory>

using namespace std;


class Animals {
private:
    std::string noise = "None";

public:
    Animals() = default;

    virtual ~Animals() = default;

    virtual std::string getNoise() {
        return noise;
    }

};

class Duck : public Animals {
private:
    std::string noise = "Quack!";
public:
    using Animals::Animals;

    std::string getNoise() override {
        return noise;
    }
};

class Dog : public Animals {
private:
    std::string noise = "Bark!";
public:
    using Animals::Animals;

    std::string getNoise() override {
        return noise;
    }
};


class AnimalsContainer {
public:
    std::vector<Animals *> animals;
    Animals *front;

    AnimalsContainer() {
        Duck duck;
        Dog dog;
        animals.push_back(&duck);
        animals.push_back(&dog);
        front = animals[0];
    }

    ~AnimalsContainer() = default;
};


int main() {
    AnimalsContainer animals;
    cout << animals.front->getNoise() << endl;

预期输出

期待

Quack!

但我得到了

None

【问题讨论】:

    标签: c++ oop polymorphism


    【解决方案1】:

    "std::string noise" 只能在基类中声明,不能在子类中声明。而是在子类的构造函数中设置噪声值。

    【讨论】:

      【解决方案2】:

      为什么不使用指针:

      Duck* duck = new Duck();
      Dog* dog = new Dog();
      animals.push_back(duck);
      animals.push_back(dog);
      

      而不是

      Duck duck;
      Dog dog;
      animals.push_back(&duck);
      animals.push_back(&dog);
      

      然后你可以在析构函数上销毁它们:

      ~AnimalsContainer() {
          for (Animals* a : animals) {
              delete a;
          }
      }
      

      如果你真的需要基类中的噪声字符串“none”。

      当然,原始指针是为了简单起见,您也许应该使用智能指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-30
        • 2015-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        相关资源
        最近更新 更多