#include <iostream> #include <string> using namespace std; //抽象类 MachinePets class MachinePets{ public: MachinePets(); MachinePets(const string s){ nickname=s; } virtual string talk() { // 纯虚函数 return 0; } string getnickname()const { return nickname; } private: string nickname; }; // 派生类 PetCats 公有继承自类 MachinePets class PetCats:public MachinePets { public: PetCats(const string s):MachinePets(s) { } string talk(){ return "says miao wu^"; } }; // 派生类 PetDogs 公有继承自类 MachinePets class PetDogs:public MachinePets{ public: PetDogs(const string s):MachinePets(s) { } string talk(){ return "says wang wang^" ; } }; void play(MachinePets *p){ cout << p->getnickname() << " says " << p->talk() << endl; } // 主函数 int main() { PetCats cat("miku"); PetDogs dog("da huang"); play(&cat); // 按照play()形参,传递参数 play(&dog); // 按照play()形参,传递参数 return 0; }