c++实验5 Part3 简单编程练习
1 #include"petcats.h" 2 #include"petdogs.h" 3 #include"machinepets.h" 4 #include<iostream> 5 #include<string> 6 using namespace std; 7 8 void play(MachinePets *p){ 9 cout<<p -> getNickname()<<" says "<<p -> talk()<<endl; 10 } 11 12 13 int main(){ 14 PetCats cat("miku"); 15 PetDogs dog("da huang"); 16 17 play(&cat); 18 play(&dog); 19 system("pause"); 20 return 0; 21 } 22 23 main
#include<string> using namespace std; #ifndef PETS_H #define PETS_H class MachinePets{ public: MachinePets(const string s):Nickname(s){} const string getNickname(); virtual string talk()=0; private: string Nickname; }; #endif
#include"machinepets.h" #include<iostream> #include<string> using namespace std; const string MachinePets::getNickname(){ return Nickname; } machinepets.cpp
#include<string> usingnamespacestd; #ifndefPETCATS_H #definePETCATS_H #include"machinepets.h" classPetCats: publicMachinePets {public: PetCats(conststrings): MachinePets(s){} stringtalk(); private:stringcatvoice;}; #endif
#include<iostream> #include<string> #include"petcats.h" #include"machinepets.h" using namespace std; string PetCats::talk(){ catvoice="miao wu~"; return catvoice; } petcats.cpp
#include<string> using namespace std; #ifndef PETDOGS_H #define PETDOGS_H #include"machinepets.h" class PetDogs : public MachinePets{ public: PetDogs(const string s):MachinePets(s){} string talk(); private: string dogvoice; }; #endif petdogs.h
#include<iostream> #include<string> #include"petdogs.h" #include"machinepets.h" using namespace std; string PetDogs::talk(){ dogvoice="wang wang~"; return dogvoice; } petdogs.cpp