《Essential C++》系列笔记之第四章(基于对象的编程风格)之第十节(重载iostream运算符)

《Essential C++》系列笔记之第四章(基于对象的编程风格)之第十节(重载iostream运算符)_第1张图片
代码实践

  • main.cpp

    #include 
    using namespace std;
    #include "Person.h"
    
    int main()
    {
    	Person P("HMJ", 12, 12345);
    	cout << P << endl;
    	cin >> P;
    	cout << P << endl;
    
    	system("pause");
    	return 0;
    }
    
  • Person.h

    #pragma once
    #include 
    using namespace std;
    #include 
    
    class Person
    {
    	friend istream& operator>>(istream&, Person&);
    	friend ostream& operator<<(ostream&, const Person&);
    public:
    	Person(string name, int age, int tel)
    		:_name(name), _age(age), _tel(tel)
    	{}
    
    	void display();
    
    private:
    	string _name;
    	int _age;
    	int _tel;
    };
    
    //需要明确地是这里什么时候应该加const
    
    ostream& operator<<(ostream&, const Person&); 
    
    istream& operator>>(istream&, Person&);
    
  • Person.cpp

    #include "Person.h"
    
    ostream& operator<<(ostream& out, const Person& per)
    {
    	out << per._name << ' '
    		<< per._age << ' '
    		<< per._tel;
    	return out;
    }
    
    istream& operator>>(istream& in, Person& per)
    {
    	in >> per._name
    		>> per._age
    		>> per._tel;
    	return in;
    }
    
    inline void Person::display()
    {
    	cout << this->_name << endl;
    	cout << this->_age << endl;
    	cout << this->_tel << endl;
    }
    

今天还是20200326 还是可以,终于把慕课刷完了

你可能感兴趣的:(《Essential,C++》系列笔记)