所以我有 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/