task4
Pets.hpp
1 #pragma once 2 #include<bits/stdc++.h> 3 using namespace std; 4 class MachinePets 5 { 6 private: 7 string nickname; 8 public: 9 MachinePets(const string s) :nickname(s) {} 10 MachinePets(MachinePets& m) :nickname(m.nickname) {} 11 string get_nickname() const { return nickname; } 12 virtual string talk() = 0; 13 }; 14 class PetCats :public MachinePets { 15 public: 16 PetCats(const string s) : MachinePets(s) {}; 17 string talk() { return "miao mu~"; } 18 }; 19 class PetDogs :public MachinePets { 20 public: 21 PetDogs(const string s) : MachinePets(s) {}; 22 string talk() { return "wang wang~"; } 23 };
task4.cpp
1 #include <iostream> 2 #include "pets.hpp" 3 4 void play(MachinePets& obj) { 5 std::cout << obj.get_nickname() << " says " << obj.talk() << std::endl; 6 } 7 8 void test() { 9 PetCats cat("miku"); 10 PetDogs dog("da huang"); 11 play(cat); 12 play(dog); 13 } 14 15 int main() { 16 test(); 17 }
标签:const,string,实验,MachinePets,return,nickname,public From: https://www.cnblogs.com/zhouxv/p/16930513.html