其他分享
首页 > 其他分享> > 实验5 模板类与多态

实验5 模板类与多态

作者:互联网

#pragma once
#include<iostream>
 #include<string>
#include <istream>
 #include <sstream>
using namespace std;
 class Person {
 private:
        string name, telephone, email;
 public:
         Person() = default;
         ~Person() = default;
         Person(string a, string b, string c = " ") :name(a), telephone(b), email(c) {    };
         void set_phone(string b);
         void set_email(string c);
         friend ostream & operator<<(ostream & out, const Person p);
         friend istream & operator>>(istream & in, Person & p);
         friend bool operator==(const Person p1, const Person p2);
    
};
 void Person::set_phone(string ss) {
         telephone = ss;
    
}

 void Person::set_email(string sss) {
         email = sss;
    
}
ostream & operator<<(ostream & out, const Person p) {
    
             out << p.name << '\t' << p.telephone << '\t' << p.email << endl;
        return out;
    
}
 istream & operator>>(istream & in, Person & p) {
        in >> ws;
         getline(in, p.name);
         in >> p.telephone >> p.email;
        return in;
    
}
 bool operator==(const Person p1, const Person p2) {
       return (p1.name == p2.name && p1.telephone == p2.telephone);
    
}
#include <iostream>
#include <fstream>
#include <vector>
#include "Person.hpp"

int main()
{
    using namespace std;

    vector<Person> phone_book;
    Person p;

    while(cin>>p)
        phone_book.push_back(p);
    
    for(auto &i: phone_book)
        cout << i << endl;
    
    cout << boolalpha << (phone_book.at(0) == phone_book.at(1)) << endl;

    ofstream fout;

    fout.open("phone_book.txt");

    if(!fout.is_open())
    {
        cerr << "fail to open file phone_book.txt\n";
        return 1;
    }

    for(auto &i: phone_book)
        fout << i << endl;
    
    fout.close();
}

 

标签:string,phone,多态,telephone,Person,实验,include,email,模板
来源: https://www.cnblogs.com/yangliu-1219/p/15686059.html