task4:
pets.hpp:
#pragma once #include<iostream> #include<string> using namespace std; class MachinePets { public: MachinePets(){ } MachinePets(const string s) :nickname(s) { } string get_nickname() const { return nickname; } virtual string talk()=0; string nickname; }; class PetDogs:public MachinePets { public: PetDogs(const string s):MachinePets(s){ } string talk() { return "wang wang~"; } }; class PetCats:public MachinePets { public: PetCats(const string s) :MachinePets(s) { } string talk() { return "miao wu~"; } };
task4.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(); }
截图:
task5:
Person.hpp:
#pragma once #include<iostream> #include<string> using namespace std; class Person{ public: Person(){} Person(string s1,string s2,string s3=" "):name(s1),telephone(s2),email(s3){} Person(Person const &p):name(p.name),telephone(p.telephone),email(p.email){} void update_telephone(){ cout<<"tel"; cin.clear(); cin>>telephone; } void update_email(){ cout<<"ema"; cin.clear(); cin>>email; } friend bool operator==( Person& a, Person& b); friend ostream& operator<<(ostream &out, Person &c); friend istream& operator>>(istream &in, Person &c); private: string name,telephone,email; }; bool operator==( Person &a, Person &b) { return (a.name==b.name && a.telephone==b.telephone); } ostream& operator<<(ostream &out, Person &c) { out << c.name << "\t" << c.telephone << "\t" << c.email; return out; } istream& operator>>(istream &in, Person &c) { in >> c.name; in >> c.telephone; in >> c.email; return in; }
task5.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(); }
截图:
task6:
= =
被保护的数据类外无法访问,我不太知道该怎么修改。
标签:string,telephone,Person,实验,MachinePets,include,name From: https://www.cnblogs.com/202183290359gyk/p/16937908.html