1.
pets.hpp.
1 #pragma once 2 #include<iostream> 3 #include<string> 4 5 using namespace std; 6 7 class MachinePets{ 8 public: 9 MachinePets(const string s):nickname(s){} 10 virtual string talk()=0; 11 string get_nickname()const{ 12 return nickname; 13 } 14 15 private: 16 string nickname; 17 }; 18 class PetCats:public MachinePets{ 19 public: 20 PetCats(const string s):MachinePets(s){}; 21 string talk(); 22 }; 23 class PetDogs:public MachinePets{ 24 public: 25 PetDogs(const string s):MachinePets(s){}; 26 string talk(); 27 }; 28 string PetCats::talk(){ 29 string s1="miao wu~"; 30 return s1; 31 } 32 string PetDogs::talk(){ 33 string s1="wang wang~"; 34 return s1; 35 }
task4.cpp:
1 #include<iostream> 2 #include"pets.hpp" 3 using namespace std; 4 void play (MachinePets &c) 5 { 6 cout<<c.get_nickname()<<" says: "<<c.talk()<<endl; 7 } 8 9 10 11 void test() 12 { 13 PetCats cat1("miku"); 14 PetDogs dog1("dahuang"); 15 play(cat1); 16 play(dog1); 17 18 } 19 int main() 20 { 21 22 test(); 23 }
在本次实验中,类的继承中需要注意的点有:
1.当派生类的对象调用派生类构造函数的时候也要完成基类的构造函数。并且,构造基类的数据域要通过构造函数。因为数据域一般都是peivate的,无法直接构造。
2.虚函数的使用。Machinepts是个抽象类。他的虚函数talk()需要到派生类中去定义。但是利用类型兼容原则,派生类的对象可以作为基类的对象使用,但是只能使用从基类及继承的成员。
编译运行结果如下:
2.Person.hpp:
1 #pragma once 2 #include<iostream> 3 #include<string> 4 #include<iomanip> 5 #include <fstream> 6 using namespace std; 7 class Person{ 8 public: 9 Person(string name1="",string telephone1="",string email1="" ):name(name1),telephone(telephone1),email(email1){} 10 Person(const Person &person1):name(person1.name),telephone(person1.telephone),email(person1.email){ }; 11 void update_telephone(); 12 void update_email(); 13 friend ostream& operator<<(ostream &out,Person &person); 14 friend istream& operator>>(istream &in,Person &person); 15 friend bool operator==(Person &person1,Person &person2); 16 17 private: 18 string name,telephone,email; 19 }; 20 ostream& operator<<(ostream &out,Person &person) 21 { 22 out<<left<<setw(15)<<person.name<<" "<<person.telephone<<" "<<person.email; 23 cout<<endl; 24 return out; 25 } 26 istream& operator>>(istream &in,Person &person){ 27 28 getline(cin,person.name); 29 getline(cin,person.telephone); 30 getline(cin,person.email); 31 cout<<endl; 32 return in; 33 } 34 bool operator==(Person &person1,Person &person2) 35 { 36 return (person1.email==person2.email&&person1.telephone==person2.telephone); 37 } 38 void Person::update_telephone() 39 {cout<<"请输入新的电话号码:"; 40 cin.clear(); 41 cin>>telephone; 42 cout<<endl; 43 cout<<"电话号码已经更新"<<endl; 44 } 45 void Person::update_email() 46 {cout<<"请输入新的邮箱地址:"; 47 cin.clear(); 48 cin>>email; 49 cout<<endl; 50 cout<<"邮箱号码已经更新"<<endl; 51 }
task5.cpp:
1 #include <iostream> 2 #include <fstream> 3 #include <vector> 4 #include "Person.hpp" 5 6 void test() { 7 using namespace std; 8 9 vector<Person> phone_book; 10 Person p; 11 12 cout << "Enter person's contact until press Ctrl + Z" << endl; 13 while(cin >> p) 14 phone_book.push_back(p); 15 16 cout << "\nupdate someone's contact: \n"; 17 phone_book.at(0).update_telephone(); 18 phone_book.at(0).update_email(); 19 20 cout << "\ndisplay all contacts' info\n"; 21 for(auto &phone: phone_book) 22 cout << phone << endl; 23 24 cout << "\ntest whether the same contact\n"; 25 cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl; 26 } 27 28 int main() { 29 test(); 30 }
1.这里应用到了运算符的重载,掌握基本语法即可。
2.这里涉及了字符串的连续的输入,可以利用cin.clear()清理输入缓存区。将之前输入区域的多余字符串删去。
task6:
1 //======================= 2 // container.h 3 //======================= 4 #pragma once 5 // The so-called inventory of a player in RPG games 6 // contains two items, heal and magic water 7 8 #ifndef _CONTAINER // Conditional compilation 9 #define _CONTAINER 10 11 class container // Inventory 12 { 13 protected: 14 int numOfHeal; // number of heal 15 int numOfMW; // number of magic water 16 public: 17 container(); // constuctor 18 void set(int heal_n, int mw_n); // set the items numbers 19 int nOfHeal(); // get the number of heal 20 int nOfMW(); // get the number of magic water 21 void display(); // display the items; 22 bool useHeal(); // use heal 23 bool useMW(); // use magic water 24 ~container()=default; 25 }; 26 27 #endif
1 //======================= 2 // container.cpp 3 //======================= 4 #include<iostream> 5 #include"container.h" 6 using namespace std; 7 // default constructor initialise the inventory as empty 8 container::container() 9 { 10 set(0,0); 11 } 12 13 // set the item numbers 14 void container::set(int heal_n, int mw_n) 15 { 16 numOfHeal=heal_n; 17 numOfMW=mw_n; 18 } 19 20 // get the number of heal 21 int container::nOfHeal() 22 { 23 return numOfHeal; 24 } 25 26 // get the number of magic water 27 int container::nOfMW() 28 { 29 return numOfMW; 30 } 31 32 // display the items; 33 void container::display() 34 { 35 cout<<"Your bag contains: "<<endl; 36 cout<<"Heal(HP+100): "<<numOfHeal<<endl; 37 cout<<"Magic Water (MP+80): "<<numOfMW<<endl; 38 } 39 40 //use heal 41 bool container::useHeal() 42 { 43 numOfHeal--; 44 return 1; // use heal successfully 45 } 46 47 //use magic water 48 bool container::useMW() 49 { 50 numOfMW--; 51 return 1; // use magic water successfully 52 }
1 //======================= 2 // player.h 3 //======================= 4 #pragma once 5 // The base class of player 6 // including the general properties and methods related to a character 7 8 #ifndef _PLAYER 9 #define _PLAYER 10 11 #include <iomanip> // use for setting field width 12 #include <time.h> // use for generating random factor 13 #include "container.h" 14 15 enum job {sw, ar, mg}; /* define 3 jobs by enumerate type 16 sword man, archer, mage */ 17 class player 18 { 19 friend void showinfo(player &p1, player &p2); 20 friend class swordsman; 21 22 protected: 23 int HP, HPmax, MP, MPmax, AP, DP, speed, EXP, LV; 24 // General properties of all characters 25 std::string name; // character name 26 job role; /* character's job, one of swordman, archer and mage, 27 as defined by the enumerate type */ 28 container bag; // character's inventory 29 30 public: 31 virtual bool attack(player &p)=0; // normal attack 32 virtual bool specialatt(player &p)=0; //special attack 33 virtual void isLevelUp()=0; // level up judgement 34 /* Attention! 35 These three methods are called "Pure virtual functions". 36 They have only declaration, but no definition. 37 The class with pure virtual functions are called "Abstract class", which can only be used to inherited, but not to constructor objects. 38 The detailed definition of these pure virtual functions will be given in subclasses. */ 39 40 void reFill(); // character's HP and MP resume 41 bool death(); // report whether character is dead 42 void isDead(); // check whether character is dead 43 bool useHeal(); // consume heal, irrelevant to job 44 bool useMW(); // consume magic water, irrelevant to job 45 void transfer(player &p); // possess opponent's items after victory 46 void showRole(); // display character's job 47 48 private: 49 bool playerdeath; // whether character is dead, doesn't need to be accessed or inherited 50 }; 51 52 #endif
1 //======================= 2 // player.cpp 3 //======================= 4 5 #include<iostream> 6 #include"player.h" 7 #include"container.cpp" 8 9 using namespace std; 10 // character's HP and MP resume 11 void player::reFill() 12 { 13 HP=HPmax; // HP and MP fully recovered 14 MP=MPmax; 15 } 16 17 // report whether character is dead 18 bool player::death() 19 { 20 return playerdeath; 21 } 22 23 // check whether character is dead 24 void player::isDead() 25 { 26 if(HP<=0) // HP less than 0, character is dead 27 { 28 cout<<name<<" is Dead." <<endl; 29 system("pause"); 30 playerdeath=1; // give the label of death value 1 31 } 32 } 33 34 // consume heal, irrelevant to job 35 bool player::useHeal() 36 { 37 if(bag.nOfHeal()>0) 38 { 39 HP=HP+100; 40 if(HP>HPmax) // HP cannot be larger than maximum value 41 HP=HPmax; // so assign it to HPmax, if necessary 42 cout<<name<<" used Heal, HP increased by 100."<<endl; 43 bag.useHeal(); // use heal 44 system("pause"); 45 return 1; // usage of heal succeed 46 } 47 else // If no more heal in bag, cannot use 48 { 49 cout<<"Sorry, you don't have heal to use."<<endl; 50 system("pause"); 51 return 0; // usage of heal failed 52 } 53 } 54 55 // consume magic water, irrelevant to job 56 bool player::useMW() 57 { 58 if(bag.nOfMW()>0) 59 { 60 MP=MP+100; 61 if(MP>MPmax) 62 MP=MPmax; 63 cout<<name<<" used Magic Water, MP increased by 100."<<endl; 64 bag.useMW(); 65 system("pause"); 66 return 1; // usage of magic water succeed 67 } 68 else 69 { 70 cout<<"Sorry, you don't have magic water to use."<<endl; 71 system("pause"); 72 return 0; // usage of magic water failed 73 } 74 } 75 76 // possess opponent's items after victory 77 void player::transfer(player &p) 78 { 79 cout<<name<<" got"<<p.bag.nOfHeal()<<" Heal, and "<<p.bag.nOfMW()<<" Magic Water."<<endl; 80 system("pause"); 81 bag.set(bag.nOfHeal()+p.bag.nOfHeal(),bag.nOfMW()+p.bag.nOfMW()); 82 // set the character's bag, get opponent's items 83 } 84 85 // display character's job 86 void player::showRole() 87 { 88 switch(role) 89 { 90 case sw: 91 cout<<"Swordsman"; 92 break; 93 case ar: 94 cout<<"Archer"; 95 break; 96 case mg: 97 cout<<"Mage"; 98 break; 99 default: 100 break; 101 } 102 } 103 104 105 // display character's job 106 void showinfo(player &p1, player &p2) 107 { 108 system("cls"); 109 cout<<"##############################################################"<<endl; 110 cout<<"# Player"<<setw(10)<<p1.name<<" LV. "<<setw(3) <<p1.LV 111 <<" # Opponent"<<setw(10)<<p2.name<<" LV. "<<setw(3) <<p2.LV<<" #"<<endl; 112 cout<<"# HP "<<setw(3)<<(p1.HP<=999?p1.HP:999)<<'/'<<setw(3)<<(p1.HPmax<=999?p1.HPmax:999) 113 <<" | MP "<<setw(3)<<(p1.MP<=999?p1.MP:999)<<'/'<<setw(3)<<(p1.MPmax<=999?p1.MPmax:999) 114 <<" # HP "<<setw(3)<<(p2.HP<=999?p2.HP:999)<<'/'<<setw(3)<<(p2.HPmax<=999?p2.HPmax:999) 115 <<" | MP "<<setw(3)<<(p2.MP<=999?p2.MP:999)<<'/'<<setw(3)<<(p2.MPmax<=999?p2.MPmax:999)<<" #"<<endl; 116 cout<<"# AP "<<setw(3)<<(p1.AP<=999?p1.AP:999) 117 <<" | DP "<<setw(3)<<(p1.DP<=999?p1.DP:999) 118 <<" | speed "<<setw(3)<<(p1.speed<=999?p1.speed:999) 119 <<" # AP "<<setw(3)<<(p2.AP<=999?p2.AP:999) 120 <<" | DP "<<setw(3)<<(p2.DP<=999?p2.DP:999) 121 <<" | speed "<<setw(3)<<(p2.speed<=999?p2.speed:999)<<" #"<<endl; 122 cout<<"# EXP"<<setw(7)<<p1.EXP<<" Job: "<<setw(7); 123 p1.showRole(); 124 cout<<" # EXP"<<setw(7)<<p2.EXP<<" Job: "<<setw(7); 125 p2.showRole(); 126 cout<<" #"<<endl; 127 cout<<"--------------------------------------------------------------"<<endl; 128 p1.bag.display(); 129 cout<<"##############################################################"<<endl; 130 }
1 //======================= 2 // swordsman.h 3 //======================= 4 5 // Derived from base class player 6 // For the job Swordsman 7 #include<iostream> 8 #include "player.h" 9 using namespace std; 10 class swordsman : public player // subclass swordsman publicly inherited from base player 11 { 12 public: 13 swordsman(int lv_in=1, string name_in="Not Given"); 14 // constructor with default level of 1 and name of "Not given" 15 void isLevelUp(); 16 bool attack (player &p); 17 bool specialatt(player &p); 18 /* These three are derived from the pure virtual functions of base class 19 The definition of them will be given in this subclass. */ 20 void AI(player &p); // Computer opponent 21 };
1 //======================= 2 // swordsman.cpp 3 //======================= 4 #include<iostream> 5 #include"swordsman.h" 6 #include"container.h" 7 #include"player.h" 8 #include"player.cpp" 9 using namespace std; 10 // constructor. default values don't need to be repeated here 11 swordsman::swordsman(int lv_in, string name_in) 12 { 13 role=sw; // enumerate type of job 14 LV=lv_in; 15 name=name_in; 16 17 // Initialising the character's properties, based on his level 18 HPmax=150+8*(LV-1); // HP increases 8 point2 per level 19 HP=HPmax; 20 MPmax=75+2*(LV-1); // MP increases 2 points per level 21 MP=MPmax; 22 AP=25+4*(LV-1); // AP increases 4 points per level 23 DP=25+4*(LV-1); // DP increases 4 points per level 24 speed=25+2*(LV-1); // speed increases 2 points per level 25 26 playerdeath=0; 27 EXP=LV*LV*75; 28 bag.set(lv_in, lv_in); 29 } 30 31 void swordsman::isLevelUp() 32 { 33 if(EXP>=LV*LV*75) 34 { 35 LV++; 36 AP+=4; 37 DP+=4; 38 HPmax+=8; 39 MPmax+=2; 40 speed+=2; 41 cout<<name<<" Level UP!"<<endl; 42 cout<<"HP improved 8 points to "<<HPmax<<endl; 43 cout<<"MP improved 2 points to "<<MPmax<<endl; 44 cout<<"Speed improved 2 points to "<<speed<<endl; 45 cout<<"AP improved 4 points to "<<AP<<endl; 46 cout<<"DP improved 5 points to "<<DP<<endl; 47 system("pause"); 48 isLevelUp(); // recursively call this function, so the character can level up multiple times if got enough exp 49 } 50 } 51 52 bool swordsman::attack(player &p) 53 { 54 double HPtemp=0; // opponent's HP decrement 55 double EXPtemp=0; // player obtained exp 56 double hit=1; // attach factor, probably give critical attack 57 srand((unsigned)time(NULL)); // generating random seed based on system time 58 59 // If speed greater than opponent, you have some possibility to do double attack 60 if ((speed>p.speed) && (rand()%100<(speed-p.speed))) // rand()%100 means generates a number no greater than 100 61 { 62 HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10)); // opponent's HP decrement calculated based their AP/DP, and uncertain chance 63 cout<<name<<"'s quick strike hit "<<p.name<<", "<<p.name<<"'s HP decreased "<<HPtemp<<endl; 64 p.HP=int(p.HP-HPtemp); 65 EXPtemp=(int)(HPtemp*1.2); 66 } 67 68 // If speed smaller than opponent, the opponent has possibility to evade 69 if ((speed<p.speed) && (rand()%50<1)) 70 { 71 cout<<name<<"'s attack has been evaded by "<<p.name<<endl; 72 system("pause"); 73 return 1; 74 } 75 76 // 10% chance give critical attack 77 if (rand()%100<=10) 78 { 79 hit=1.5; 80 cout<<"Critical attack: "; 81 } 82 83 // Normal attack 84 HPtemp=(int)((1.0*AP/p.DP)*AP*5/(rand()%4+10)); 85 cout<<name<<" uses bash, "<<p.name<<"'s HP decreases "<<HPtemp<<endl; 86 EXPtemp=(int)(EXPtemp+HPtemp*1.2); 87 p.HP=(int)(p.HP-HPtemp); 88 cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl; 89 EXP=(int)(EXP+EXPtemp); 90 system("pause"); 91 return 1; // Attack success 92 } 93 94 bool swordsman::specialatt(player &p) 95 { 96 if(MP<40) 97 { 98 cout<<"You don't have enough magic points!"<<endl; 99 system("pause"); 100 return 0; // Attack failed 101 } 102 else 103 { 104 MP-=40; // consume 40 MP to do special attack 105 106 //10% chance opponent evades 107 if(rand()%100<=10) 108 { 109 cout<<name<<"'s leap attack has been evaded by "<<p.name<<endl; 110 system("pause"); 111 return 1; 112 } 113 114 double HPtemp=0; 115 double EXPtemp=0; 116 //double hit=1; 117 //srand(time(NULL)); 118 HPtemp=(int)(AP*1.2+20); // not related to opponent's DP 119 EXPtemp=(int)(HPtemp*1.5); // special attack provides more experience 120 cout<<name<<" uses leap attack, "<<p.name<<"'s HP decreases "<<HPtemp<<endl; 121 cout<<name<<" obtained "<<EXPtemp<<" experience."<<endl; 122 p.HP=(int)(p.HP-HPtemp); 123 EXP=(int)(EXP+EXPtemp); 124 system("pause"); 125 } 126 return 1; // special attack succeed 127 } 128 129 // Computer opponent 130 void swordsman::AI(player &p) 131 { 132 if ((HP<(int)((1.0*p.AP/DP)*p.AP*1.5))&&(HP+100<=1.1*HPmax)&&(bag.nOfHeal()>0)&&(HP>(int)((1.0*p.AP/DP)*p.AP*0.5))) 133 // AI's HP cannot sustain 3 rounds && not too lavish && still has heal && won't be killed in next round 134 { 135 useHeal(); 136 } 137 else 138 { 139 if(MP>=40 && HP>0.5*HPmax && rand()%100<=30) 140 // AI has enough MP, it has 30% to make special attack 141 { 142 specialatt(p); 143 p.isDead(); // check whether player is dead 144 } 145 else 146 { 147 if (MP<40 && HP>0.5*HPmax && bag.nOfMW()) 148 // Not enough MP && HP is safe && still has magic water 149 { 150 useMW(); 151 } 152 else 153 { 154 attack(p); // normal attack 155 p.isDead(); 156 } 157 } 158 } 159 }
//======================= // main.cpp //======================= // main function for the RPG style game #include <iostream> #include <string> using namespace std; #include "swordsman.cpp" int main() { string tempName; bool success=0; //flag for storing whether operation is successful cout <<"Please input player's name: "; cin >>tempName; // get player's name from keyboard input player *human; // use pointer of base class, convenience for polymorphism int tempJob; // temp choice for job selection do { cout <<"Please choose a job: 1 Swordsman, 2 Archer, 3 Mage"<<endl; cin>>tempJob; system("cls"); // clear the screen switch(tempJob) { case 1: human=new swordsman(1,tempName); // create the character with user inputted name and job success=1; // operation succeed break; default: break; // In this case, success=0, character creation failed } }while(success!=1); // so the loop will ask user to re-create a character int tempCom; // temp command inputted by user int nOpp=0; // the Nth opponent for(int i=1;nOpp<5;i+=2) // i is opponent's level { nOpp++; system("cls"); cout<<"STAGE" <<nOpp<<endl; cout<<"Your opponent, a Level "<<i<<" Swordsman."<<endl; system("pause"); swordsman enemy(i, "Warrior"); // Initialise an opponent, level i, name "Junior" human->reFill(); // get HP/MP refill before start fight while(!human->death() && !enemy.death()) // no died { success=0; while (success!=1) { showinfo(*human,enemy); // show fighter's information cout<<"Please give command: "<<endl; cout<<"1 Attack; 2 Special Attack; 3 Use Heal; 4 Use Magic Water; 0 Exit Game"<<endl; cin>>tempCom; switch(tempCom) { case 0: cout<<"Are you sure to exit? Y/N"<<endl; char temp; cin>>temp; if(temp=='Y'||temp=='y') return 0; else break; case 1: success=human->attack(enemy); human->isLevelUp(); enemy.isDead(); break; case 2: success=human->specialatt(enemy); human->isLevelUp(); enemy.isDead(); break; case 3: success=human->useHeal(); break; case 4: success=human->useMW(); break; default: break; } } if(!enemy.death()) // If AI still alive enemy.AI(*human); else // AI died { cout<<"YOU WIN"<<endl; human->transfer(enemy); // player got all AI's items } if (human->death()) { system("cls"); cout<<endl<<setw(50)<<"GAME OVER"<<endl; human->isDead() ; // player is dead, program is getting to its end, what should we do here? system("pause"); return 0; } } } delete human; // You win, program is getting to its end, what should we do here? system("cls"); cout<<"Congratulations! You defeated all opponents!!"<<endl; system("pause"); return 0; }
实验总结:
1.本次实验主要掌握了类的继承和操作符重载的语法知识。并且,还对编译时多态和运行时多态进行了体验。
2。同时,也对c++中的库函数中的map进行了相应的体验。
标签:string,继承,void,player,int,实验,include,HP From: https://www.cnblogs.com/xiaozhengcaicai/p/16927604.html