设计并实现一个机器宠物类MachinePets。

  • 每个机器宠物有如下信息:昵称(nickname)
  • 每个机器宠物有如下成员函数:
    • 带参数的构造函数MachinePets(const string s) ,为机器宠物初始化昵称。 纯虚函数
    • string talk()为机器宠物派生类提供宠物叫声的统一接口。

设计并实现电子宠物猫类PetCats,该类公有继承自MachinePets。每个电子宠物猫类有如下成员函数:

  • 带参数的构造函数PetCats(const string s),为机器宠物猫初始化昵称。
  • string talk(),返回电子宠物猫叫声。 

设计并实现电子宠物狗类PetDogs, 该类公有继承自MachinePets。每个电子宠物狗类有如下成员函数:

  • 带参数的构造函数PetCats(const string s),为机器宠物狗初始化昵称。
  • string talk(),返回电子宠物狗叫声。

编程实现上述三个类,并编写一个统一的接口函数void play(××),可以根据实参对象的类型,显示不同宠物叫声。 最后,编写主函数,在主函数中定义电子宠物猫PetCats类对象和电子宠物狗PetDogs类对象,并调用接口函数,运行测试。

 1 #ifndef _MACHINEPETS_
 2 #define _MACHINEPETS_
 3 
 4 #include <string>
 5 
 6 using std::string;
 7 
 8 class MachinePets
 9 {
10 public:
11     MachinePets(const string s):nickname(s) {};
12     ~MachinePets() {};
13     string getNickname() {
14         return nickname;
15     };
16     virtual string talk() = 0;
17 
18 private:
19     string nickname;
20 };
21 
22 #endif // !_MACHINEPETS_
machinepets.h
 1 #ifndef _PETCATS_
 2 #define _PETCATS_
 3 
 4 #include <string>
 5 #include "machinepets.h";
 6 
 7 using std::string;
 8 
 9 class PetCats:public MachinePets
10 {
11 public:
12     PetCats(const string s):MachinePets(s) {};
13     ~PetCats() {};
14     string talk() {
15         return "miao wu~";
16     };
17 };
18 
19 #endif // _PETCATS_
petcats.h
 1 #ifndef _PETDOGS_
 2 #define _PETDOGS_
 3 
 4 #include <string>
 5 #include "machinepets.h";
 6 
 7 using std::string;
 8 
 9 class PetDogs :public MachinePets
10 {
11 public:
12     PetDogs(const string s):MachinePets(s) {};
13     ~PetDogs() {};
14     string talk() {
15         return "wang wang~";
16     };
17 };
18 
19 #endif // _PETDOGS_
petdogs.h
 1 #include "machinepets.h"
 2 #include "petcats.h"
 3 #include "petdogs.h"
 4 
 5 #include <iostream>
 6 
 7 using std::cout;
 8 using std::endl;
 9 
10 void play(MachinePets *p) {
11     cout << p->getNickname() << " say " << p->talk() << endl;
12 }
13 
14 int main() {
15     PetCats cat("miku");
16     PetDogs dog("da huang");
17     play(&cat);
18     play(&dog);
19     return 0; 
20 }
main.cpp

总结与体会

这一次碰到了一个之前从来没有见过的报错,是一次全新的体验,回去之后尝试了一下,好像是语句写错了,稍微改了一下原来的程序也能顺利运行,以后写这些东西应该多注意一下。

 

posted on 2019-06-02 18:54  Nibelungenlied  阅读(147)  评论(0编辑  收藏  举报