实验5
#pragma once #include<string> using namespace std; class MachinePets { public: MachinePets(const string s); ~MachinePets(); const string getNickname(); virtual string talk(); private: string nickname; };
#pragma once #include<iostream> #include<string> using namespace std; #include "MachinePets.h" class PetCats : public MachinePets { public: PetCats(const string s); ~PetCats(); string talk(); };
#pragma once #include "MachinePets.h" #include<iostream> #include<string> using namespace std; class PetDogs : public MachinePets { public: PetDogs(const string s); ~PetDogs(); string talk(); };
#include "MachinePets.h" #include<iostream> #include<string> using namespace std; MachinePets::MachinePets(const string s):nickname(s) { } MachinePets::~MachinePets() { } const string MachinePets::getNickname() { return string(nickname); } string MachinePets::talk() { return string(); }
#include "PetCats.h" #include<iostream> #include<string> using namespace std; PetCats::PetCats(const string s):MachinePets(s) { } PetCats::~PetCats() { } string PetCats::talk() { return string("miao wu~"); }
#include "PetDogs.h" #include<iostream> #include<string> using namespace std; PetDogs::PetDogs(const string s):MachinePets(s) { } PetDogs::~PetDogs() { } string PetDogs::talk() { return string("wang wang~"); }
#include"MachinePets.h" #include"PetCats.h" #include"PetDogs.h" #include<iostream> using namespace std; void play(MachinePets* ptr) { cout << ptr->getNickname() << " says " << ptr->talk() << endl; } int main() { PetCats cat("miku"); PetDogs dog("da huang"); play(&cat); // 按照play()形参,传递参数 play(&dog); // 按照play()形参,传递参数 system("pause"); return 0; }