加号和左移运算符重载

#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <string>
#include <queue>

#include <fstream> // c++文件操作
#include <iomanip> // 设置输出格式

#include <numeric>
#include <algorithm>
#include <unordered_set>
#include "for_code.h"

using namespace std;

class Person{
    
    

    friend ostream & operator<<(ostream &cout, Person &p);

    public:
        // + 重载
        Person operator+(Person &p)
        {
    
    
            Person temp;
            temp.m_A = this->m_A + p.m_A; //this指向被调用的成员函数所属的对象
            temp.m_B = this->m_B + p.m_B;
            return temp;
        }

    public:

        Person(){
    
    }

        Person(int a, int b)
        {
    
    
            m_A = a;
            m_B = b;
        }

    private:
        int m_A;
        int m_B;

};

// << 重载
ostream & operator<<(ostream &cout, Person &p)
{
    
    
    cout << "p.m_A" << p.m_A << ",p.m_B" << p.m_B;
}

int main(int argc, char const *argv[])
{
    
    
    Person p1(10,20);

    Person p2(10,20);

    cout << p1 << ",hi" << endl;


    // Person p3 = p1.operator+(p2);
    Person p3 = p1 + p2;

    cout << p3 << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35632833/article/details/113155433
今日推荐