C++(实验五)

Part1 验证性实验

 1.通过"对象名.成员名"访问类族中同名成员函数时运行结果为派生类的成员函数

 2.通过基类指针访问派生类对象时,基类中成员函数有关键字virtual,访问的为派生类对象,无关键字访问的为基类对象 

 

Part2 简单编程练习

设计并实现一个机器宠物类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_H
 2 #define MACHINEPETS_H
 3 #include <string>
 4 using namespace std;
 5 
 6 class MachinePets{
 7 public:
 8     MachinePets(const string s);
 9     const string getNickname();
10     virtual string talk()=0;
11 private:
12     string nickname;
13 };
14 #endif
MachinePets.h
 1 #include "MachinePets.h"
 2 using namespace std;
 3 
 4 MachinePets::MachinePets(const string s):nickname(s){
 5 }
 6 
 7 const string MachinePets::getNickname(){
 8   return nickname;
 9 }
10 
11 string MachinePets::talk(){
12     string t;
13     t="wang wang wang";
14     return t;
15 }
MachinePets.cpp
 1 #include "PetCats.h"
 2 using namespace std;
 3 
 4 PetCats::PetCats(const string s):MachinePets(s){
 5 }
 6 
 7 string PetCats::talk(){
 8     string t;
 9     t="miao wu~";
10     return t;
11 }
PetCats.cpp
 1 #ifndef PETCATS_H
 2 #define PETCATS_H
 3 #include "MachinePets.h"
 4 #include <string>
 5 
 6 class PetCats:public MachinePets{
 7 public:
 8     PetCats(const string s);
 9     string talk();
10     friend void play();
11 };
12 #endif
PetCats.h
 1 #include "PetDogs.h"
 2 using namespace std;
 3 
 4 PetDogs::PetDogs(const string s):MachinePets(s){
 5 }
 6 
 7 string PetDogs::talk(){
 8     string t;
 9     t="wang wang~";
10     return t;
11 }
PetDogs.cpp
 1 #ifndef PETDOGS_H
 2 #define PETDOGS_H
 3 #include "MachinePets.h"
 4 #include <string>
 5 
 6 class PetDogs:public MachinePets{
 7 public:
 8     PetDogs(const string s);
 9     string talk();
10     friend void play();
11 };
12 #endif
PetDogs.h
 1 #include "PetCats.h"
 2 #include "PetDogs.h"
 3 #include "MachinePets.h"
 4 #include <iostream>
 5 using namespace std;
 6 
 7 void play(MachinePets *p){
 8     cout<<p->getNickname()<<" "<<"says"<<" "<<p->talk()<<endl;
 9 }
10 
11 int main() {
12 PetCats cat("miku");
13 PetDogs dog("da huang");
14 play(&cat);
15 play(&dog);
16 return 0;
17 }
main.cpp

运行截图:

 

 

 实验总结:

 1.尝试使用公共接口函数和关键字virtual

 2.通过此次实践进一步学习了类的继承与派生,并对此有了新的理解

 3.通过part3 发现自己对string、类的访问方式相关的知识点已遗忘,及时查漏补缺进行巩固

 

实验四评论链接:

https://www.cnblogs.com/joey-yan/p/10856607.html

https://www.cnblogs.com/fearless04/p/10890542.html

https://www.cnblogs.com/csc13813017371/p/10886674.html

posted @ 2019-06-03 16:31  糕点点  阅读(253)  评论(1编辑  收藏  举报