#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;
}
C++: 简单运算符重载(加法, 减法, 前后置++, 输入, 输出)
最新推荐文章于 2022-10-24 09:08:15 发布