#ifndef MACHINEPETS_H #define MACHINEPETS_H #include <iostream> #include <string> using namespace std; class MachinePets { public: MachinePets(const string s); string getNickname(); virtual string talk()=0; private: string Nickname; }; #endif
#include "MachinePets.h" #include <iostream> #include <string> using namespace std; MachinePets::MachinePets(const string s):Nickname(s){ } string MachinePets::getNickname(){ return Nickname;}
#ifndef PETCATS_H #define PETCATS_H #include "MachinePets.h" class PetCats:public MachinePets { public: PetCats(const string s); string talk(); private: string catname; }; #endif
#include <iostream> #include "MachinePets.h" #include "PetCats.h" using namespace std; PetCats::PetCats(const string s):MachinePets(s){ } string PetCats::talk(){ return "miao wu~";}
#ifndef PETDOGS_H #define PETDOGS_H #include "MachinePets.h" class PetDogs:public MachinePets { public: PetDogs(const string s); string talk(); private: string Nickname; }; #endif
#include <iostream> #include "MachinePets.h" #include "PetDogs.h" using namespace std; PetDogs::PetDogs(const string s):MachinePets(s){ } string PetDogs::talk(){ return "wang wang~";}
#include <iostream> #include <string> #include "MachinePets.h" #include "PetCats.h" #include "PetDogs.h" using namespace std; void play(MachinePets *p) { cout << p->getNickname() << " says " << p->talk() << endl; } int main() { PetCats cat("miku"); PetDogs dog("da huang"); play(&cat); play(&dog); system ("pause"); return 0; }
总结:程序都是在课上完成的,回来运行时出现找不到play标识符,然后百度之后换了void和int main的顺序就对了