C++ 继承。对象调用父类(super class)方法而不是它自己的方法?

标签 c++ polymorphism

所以我有 2 个类,

class Animal{
public:
    Animal(int age, int hairCount) {
        howOld = age;
        numOfHairs = hairCount;
    }

    void print(){
        cout << "Age: " << howOld << "\tNumber of Hairs: " << numOfHairs << endl;
    }

protected:
    int howOld;
    int numOfHairs;
};



class Bird: public Animal{
public:
    Bird(int age, int hairCount, bool fly) : Animal(age, hairCount) {
        canItFly = fly;
    }

    void print() {
        cout << "Age: " << howOld << "\tNumber of Hairs: " 
             << numOfHairs << "\tAbility to fly: " << canItFly << endl;
    }
protected:
    bool canItFly;
};

如果在主程序中,我有这样的东西:

#include <vector>
#include <iostream>
using namespace std;

int main() {
    vector<Animal> list;
    list.pushBack(Bird(5,10000,true));
    list.pushBack(Animal(14,1234567));

    for(int i = 0; i < list.size(); i++){
        list[i].print(); //Calls the super class for both outputs
    }
    return 0;
}

出于某种原因,我的代码(不是这个)在这两种情况下都调用父类(super class)的打印方法。

最佳答案

你应该声明一个成员函数

void print()

虚拟即

virtual void print()

除此之外,您还应该创建一个指向 Animal 的指针 vector

vector<Animal *>

在 main 中使用 new 创建新对象。然后它将按预期工作。那就是说你的主要应该是这样的

vector<Animal *> list;
Animal *bird = new Bird(5,10000,true);
Animal *animal = new Animal(14,1234567);
list.push_back(bird);
list.push_back(animal);

如果您不再需要鸟类和动物,请不要忘记删除它们

delete bird;
delete animal;

您可以选择使用智能指针类之一,正如 Benjamin Lindley 所建议的那样。

关于C++ 继承。对象调用父类(super class)方法而不是它自己的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8221078/

相关文章:

c++ - 临时修改 const 成员函数中的字段

c++ - 通用函数返回函数指针的特化类

c++ - C++ 中#define 指令的用途是什么?

java - 多态性和接口(interface) - 澄清?

c++ - 同类容器、派生类、初始化列表和移动语义

c++ - ostream cout 和 char *

c++ - 为什么我们需要在 move 构造函数中将右值引用设置为空?

java - JVM如何解析java中的重写和覆盖方法

java - 无效类异常 : please help getting these errors

c++ - 多态对象复制