C++ 结构体重载

结构体一般都会定义相关的构造、重载函数,虽然很简单,但是有时候徒手又想不起来,所以记录一下。

#include <iostream>
using namespace std;

struct Point
{
    int x;
    int y;

    Point(int X = 0, int Y = 0)
        :x(X), y(Y)
    {

    }

    friend ostream& operator << (ostream &Out, const Point &P)
    {
        Out << "x:" << P.x << " " << "y:" << P.y;
        return Out;
    }

    friend istream& operator >> (istream &in, const Point &p)
    {
       // in >> p.x >> p.y;
        return in;
    }

    //重载<,成员函数
    bool operator < (const Point& P)const
    {
        return x < P.x;
    }
    //重载>友元函数
    friend bool operator > (const Point &a,const Point &b)
    {
        return a.x > b.x ;
    }
    //重载+,调用构造函数
    friend Point operator + (const Point& A,const Point& B)
    {
        return Point(A.x + B.x, A.y + B.y);
    }
};

使用方法:

    //初始化
    Point A(0, 1),b(2, 3);    
    cout << A<<b << endl;
    cout << (A>b) << endl << (A<b) << endl;
    cout << A+b << endl;

输出结果:

猜你喜欢

转载自blog.csdn.net/qq_19967643/article/details/88819501