子类的成员变量和父类的string都进去了 但是不知道为什么 printinfo函数打印不出来 试了好多次都不行 我电脑坏了吗
#pragma once
class Animal {
public:
Animal(std::string name,int age) {
this->_name = name;
this->_age = age;
}
virtual void printInfo() {
}
protected:
std::string _name;
int _age;
};
class Zebra:public Animal {
public:
Zebra(std::string name, int age, int numStripes) :Animal(name, age) {
_numStripes = numStripes;
}
void printInfo() {
std::cout << "Zebra, Name: " << this->_name << ", Age: " << Animal::_age << ", Number of stripes: " << Zebra::_numStripes << std::endl;
}
protected:
int _numStripes;
};
class Cat :public Animal {
public:
Cat(std::string name, int age, std::string favoriteToy) :Animal(name, age) {
this->_favoriteToy = favoriteToy;
}
virtual void printInfo() {
std::cout << "Cat, Name: " << this->_name << ", Age: " << Animal::_age << ", Favorite of stripes: " << this->_favoriteToy << std::endl;
}
protected:
std::string _favoriteToy;
};
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include"animal.h"
using namespace std;
int main() {
vector<Animal*> animal;
while (1) {
string input_string;
getline(cin, input_string);
stringstream ss(input_string);
string str;
ss >> str;
if (str == "z") {
string name;
ss >> name;
int age;
ss >> age;
int numStripes;
ss >> numStripes;
Zebra z1(name, age, numStripes);
animal.push_back(&z1);
}
if (str == "c") {
string name;
ss >> name;
int age;
ss >> age;
string favoriteToy;
ss >> favoriteToy;
Cat c1(name, age, favoriteToy);
animal.push_back(&c1);
}
if (str == "0") {
for (int i = 0; i < animal.size(); i++) {
animal[i]->printInfo();
}
break;
}
}
return 0;
}