/*问题描述*/
设计并实现一个机器宠物类MachinePets。 每个机器宠物有如下信息:昵称(nickname) 每个机器宠物有如下成员函数: 带参数的构造函数MachinePets(const string s) ,为机器宠物初始化昵称。 纯虚函数string talk()为机器宠物派生类提供宠物叫声的统一接口。
设计并实现电子宠物猫类PetCats,该类公有继承自MachinePets。每个电子宠物猫类有如下成员函数: 带参数的构造函数PetCats(const string s),为机器宠物猫初始化昵称。 string talk(),返回电子宠物猫叫声。 设计并实现电子宠物狗类PetDogs, 该类公有继承自MachinePets。每个电子宠物狗类有如下成员函数:
带参数的构造函数PetCats(const string s),为机器宠物狗初始化昵称。 string talk(),返回电子宠物狗叫声。
/*代码如下*/
1 #include "pch.h" 2 #include <iostream> 3 #include<string> 4 using std::cin; 5 using std::cout; 6 using std::endl; 7 using std::string;//引用程序所需的函数标准声明,便于在型程序出错时找错,养成良好习惯。 8 9 class machine_pets {//电子宠物类 10 public: 11 machine_pets(){} 12 machine_pets(const string str) { 13 nickname = str; 14 } 15 virtual void talk() { 16 } 17 void getnickname(string s) { 18 nickname = s; 19 } 20 private: 21 string nickname; 22 }; 23 24 class pet_cats:public machine_pets {//公有继承自电子宠物类的电子猫类 25 public: 26 pet_cats(const string name0){ 27 name = name0; 28 } 29 void talk() { 30 cout << name << " says : " << words << endl; 31 } 32 private: 33 string name; 34 string words = "miao wu``";//此处可以通过参数自行设置宠物的声音 35 }; 36 37 class pet_dogs :public machine_pets {//公有继承自电子宠物类的电子狗类 38 public: 39 pet_dogs(const string name0) { 40 name = name0; 41 } 42 void talk() { 43 cout << name << " says : " << words << endl; 44 } 45 private: 46 string name; 47 string words = "wang wang``"; 48 }; 49 50 void play(machine_pets *pets) {//公共接口函数,用于发出叫声, 51 pets->talk(); 52 } 53 54 int main() { 55 pet_cats cat("hello kitty"); 56 pet_dogs dog("superdog"); 57 58 play(&cat); 59 play(&dog); 60 61 system("pause"); 62 return 0; 63 }
/*运行截图*/
/*拓展部分*/
我们可以尝试通过音频调用的函数,以文件名作为参数等方法,来调用音频文件,使得宠物可以发出猫猫狗狗的叫声
这里给出一段参考性的代码
1 #include <windows.h> 2 #include<stdio.h> 3 #include <mmsystem.h> 4 #pragma comment(lib, "winmm.lib") 5 6 int main() 7 { 8 int mp3_alltime=0; 9 mciSendString("open \"C:\\Users\\Administrator\\Desktop\\M2M Pretty Boy.wav\" alias mp3_music",NULL,0,NULL); //需要更改 10 //播放音乐 11 mciSendString("play mp3_music",NULL,0,NULL); 12 //获取播放时间 13 char sPosition[500]; 14 mciSendString("status mp3_music length",sPosition,225,0); 15 mp3_alltime=atol(sPosition); 16 Sleep(mp3_alltime); 17 return 0; 18 }
关于Part4的一点小说明
老师提供了一个RPG游戏的基本代码,我尝试了改动,但是效果不太明显,emmm,计划周末搞一下,平时没有这么集中的时间。后续会更新的,嘻嘻嘻。