实验五
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef MACHINEPETS_H #define MACHINEPETS_H #include <string> using namespace std; class machinepets{ public: machinepets(const string s); virtual string talk()=0; string getnickname(); private: string nickname; }; #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef PETDOGS_H #define PETDOGS_H #include "machinepets.h" #include<string> using namespace std; class petdogs : public machinepets { public: petdogs(const string s); string talk(); }; #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef PETCATS_H #define PETCATS_H #include "machinepets.h" #include<string> using namespace std; class petcats : public machinepets { public: petcats(const string s); string talk(); }; #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "machinepets.h" #include <string> #include <iostream> using namespace std; machinepets::machinepets(string s):nickname(s){} string machinepets::getnickname(){ return nickname; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "petcats.h" #include <iostream> using namespace std; petcats::petcats(string s):machinepets(s){} string petcats::talk(){ return "miao wu~"; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef PETDOGS_H #define PETDOGS_H #include "machinepets.h" #include<string> using namespace std; class petdogs : public machinepets { public: petdogs(const string s); string talk(); }; #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "petcats.h" #include "petdogs.h" #include "machinepets.h" #include <iostream> using namespace std; void play(machinepets *p){ cout<<p->getnickname()<<ends<<"says"<<ends<<p->talk()<<endl; } int main(){ petcats cat("miku"); petdogs dog("da hunag"); play(&cat); play(&dog); system ("pause"); return 0; }
实验结论 :
了解虚函数的使用和意义,编写子程序作为接口通过指针访问派生类的同名函数;