任务3
源码:
1 #pragma once 2 3 #include <iostream> 4 #include <string> 5 6 using std::string; 7 8 9 class MachinePets { 10 public: 11 MachinePets(const string &s); 12 13 public: 14 virtual string get_nickname() const = 0; 15 virtual string talk() const = 0; 16 17 protected: 18 string nickname; 19 }; 20 21 MachinePets::MachinePets(const string &s): nickname{s} { 22 } 23 24 25 26 class PetCats: public MachinePets { 27 public: 28 PetCats(const string &s); 29 30 public: 31 string get_nickname() const override; 32 string talk() const override; 33 34 }; 35 36 PetCats::PetCats(const string &s): MachinePets{s} { 37 } 38 39 string PetCats::get_nickname() const{ 40 return nickname; 41 } 42 43 string PetCats::talk() const { 44 return "miao wu~"; 45 } 46 47 48 class PetDogs: public MachinePets { 49 public: 50 PetDogs(const string &s); 51 52 public: 53 string get_nickname() const override; 54 string talk() const override; 55 56 }; 57 58 PetDogs::PetDogs(const string &s): MachinePets{s} { 59 } 60 61 string PetDogs::get_nickname() const{ 62 return nickname; 63 } 64 65 string PetDogs::talk() const { 66 return "wang wang~"; 67 }pets.hpp
1 #include <iostream> 2 #include <vector> 3 #include "pets.hpp" 4 5 void test() { 6 using namespace std; 7 8 vector<MachinePets *> pets; 9 10 pets.push_back(new PetCats("miku")); 11 pets.push_back(new PetDogs("da huang")); 12 13 for(auto &ptr: pets) 14 cout <<ptr->get_nickname() << " says " << ptr->talk() << endl; 15 } 16 17 int main() { 18 test(); 19 }task3.cpp
运行测试截图:
任务4
源码:
标签:PetDogs,const,string,继承,多态,实验,MachinePets,nickname,public From: https://www.cnblogs.com/c-929/p/18582306