C++: 简单运算符重载(加法, 减法, 前后置++, 输入, 输出)

#include <iostream>
using namespace std;

class Point
{
private:
    int m_x;
    int m_y;
public:
    Point();
    Point(int x, int y);

    friend Point operator+(const Point& t1, const Point& t2);       //加法
    friend Point operator-(const Point& t1, const Point& t2);       //减法
    friend ostream& operator<<(ostream& cout, const Point& t);//输出运算符
    friend istream& operator>>(istream& cin, Point& t); //输入运算符

    Point operator-();                     //单目运算符-号
    Point operator++();                     //前置++
    const Point operator++(int);            //后置++

    ~Point();
};

Point::Point()
{
}

Point::Point(int x, int y)
{
    m_x = x;
    m_y = y;
}

Point operator+(const Point& t1, const Point& t2)
{
    Point tmp;
    tmp.m_x = t1.m_x + t2.m_x;
    tmp.m_y = t1.m_y + t2.m_y;

    return tmp;
}

Point operator-(const Point& t1, const Point& t2)
{
    Point tmp;
    tmp.m_x = t1.m_x - t2.m_x;
    tmp.m_y = t1.m_y - t2.m_y;

    return tmp;
}

ostream& operator<<(ostream& cout, const Point& t)
{
    cout << "(" << t.m_x << "," << t.m_y << ")" << endl;

    return cout;
}

istream& operator>>(istream& cin, Point& t)
{
    cout << "Please enter the abscissa:";
    cin >> t.m_x;
    cout << "Please enter the ordinate:";
    cin >> t.m_y;

    return cin;
}

Point Point::operator-()
{

    return Point(-m_x, -m_y);
}

Point Point::operator++()
{
    this->m_x += 1;
    this->m_y += 1;

    return *this;
}

const Point Point::operator++(int)
{
    Point tmp(*this);
    this->m_x += 1;
    this->m_y += 1;

    return tmp;
}

Point::~Point()
{
}

int main()
{
    Point a(10,20);
    // cin >> a;
    cout << "a:" << a;
    cout << endl;

    cout << "a++:" << a++;
    cout << "a:" << a;
    cout << endl;

    cout << "++a:" << ++a;
    cout << "a:" << a;
    cout << endl;

    cout << "-a:" << -a;
    cout << "a:" << a;
    cout << endl;

    Point b(3,4);
    cout << "b:" << b;
    cout << "a + b:" << a + b;
    cout << "a - b:" << a - b;
}

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值