task.4
cpp
#include <iostream> #include "Pets.hpp" void play(MachinePets &obj) { std::cout << obj.get_nickname() << " says " << obj.talk() << std::endl; } void test() { PetCats cat("miku"); PetDogs dog("da huang"); play( cat ); play( dog ); } int main() { test(); }
hpp
#pragma once #include <iostream> #include <string> using namespace std; using std::string; class MachinePets { public: MachinePets(const string name) : nickname{name} {} ~MachinePets() = default; string get_nickname() const { return nickname; } virtual string talk() = 0; private: string nickname; }; class PetCats : public MachinePets { public: PetCats(const string str) : MachinePets(str) {} ~PetCats() = default; string talk() { return "miao wu~"; } }; class PetDogs : public MachinePets { public: PetDogs(const string s) : MachinePets(s) {} ~PetDogs() = default; string talk() { return "wang wang~"; } };
task.5
cpp
#include <iostream> #include <fstream> #include <vector> #include "Person.hpp" void test() { using namespace std; vector<Person> phone_book; Person p; cout << "Enter person's contact until press Ctrl + Z" << endl; while(cin >> p) phone_book.push_back(p); cout << "\nupdate someone's contact: \n"; phone_book.at(0).update_telephone(); phone_book.at(0).update_email(); cout << "\ndisplay all contacts' info\n"; for(auto &phone: phone_book) cout << phone << endl; cout << "\ntest whether the same contact\n"; cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl; } int main() { test(); }
hpp
#pragma once #include <iostream> #include <string> using namespace std; using std::cin; using std::cout; using std::endl; using std::string; class Person { public: Person(string n = " ", string t = " ", string e = " ") : name{n}, telephone{t}, email{e} {} Person(const Person &p) : name{p.name}, telephone{p.telephone}, email{p.email} {} ~Person() = default; void update_telephone(); void update_email(); friend std::ostream &operator<<(std::ostream &out, Person &p); friend std::istream &operator>>(std::istream &in, Person &p); friend bool operator==(Person &p1, Person &p2); private: string name,telephone,email; }; void Person::update_telephone() { cout << "Enter the telephone number: "; cin.clear(); string new_telephone; cin>>new_telephone; telephone = new_telephone; cout<<"telephone number has been updated"<< endl; } void Person::update_email() { cout << "Enter the email address: "; string new_email; cin.clear(); cin >> new_email; cout << "email address has been updated..." << endl; email = new_email; }
标签:std,string,telephone,Person,实验,MachinePets,include From: https://www.cnblogs.com/lxyyyds/p/16938117.html