Java教程

实验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();
}

 

这篇关于实验5 模板类与多态的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!