因此,我有2个班级。
class Animal{
public:
Animal(int age, int hairCount) {
howOld = age;
numOfHairs = hairCount;
}
void print(){
cout << "Age: " << howOld << " Number 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 << " Number of Hairs: "
<< numOfHairs << " Ability to fly: " << canItFly << endl;
}
protected:
bool canItFly;
};
If in the main program, I have something like this:
#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;
}
出于某种原因,我的代码(斜线)在这两种情况下都使用超级印刷方法。