实验5 类的继承、派生和多态(2)
作者:互联网
设计并实现一个机器宠物类MachinePets。
#include"petcats.h" #include"petdogs.h" #include"machinepets.h" #include<iostream> #include<string> 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; }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; }; #endifmachinepets.h
#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;};#endifpetcats.h
#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; }; #endifpetdogs.h
#include<iostream> #include<string> #include"petdogs.h" #include"machinepets.h" using namespace std; string PetDogs::talk(){ dogvoice="wang wang~"; return dogvoice; }petdogs.cpp
这个实验相较于之前比较简单,还是要熟悉构造函数,以及熟练掌握类的继承派生,注意头文件和源文件要相对应,不然会出错。
标签:string,派生,继承,namespace,多态,machinepets,MachinePets,using,include 来源: https://www.cnblogs.com/jackyayue/p/10963492.html