#include<iostream>
using namespace std;
class coordinate{
public:
int x; //x坐标
int y; //y坐标
coordinate(); //默认构造函数1
coordinate(int x0, int y0); //重载构造函数2
void print(void); //打印属性信息函数声明
//定义运算符+的重载
coordinate operator+(coordinate& other); //运算符+重载声明
};
//默认构造函数定义
coordinate::coordinate()
{
x = 0;
y = 0;
}
//重载构造函数定义
coordinate::coordinate(int x0, int y0)
{
x = x0;
y = y0;
}
//打印属性信息函数定义
void coordinate::print()
{
cout << "(" << x << "," << y << ")" << endl;
}
//运算符+重载函数定义
coordinate coordinate::operator+(coordinate& other)
{
coordinate temp;
temp.x = this->x + other.x;
temp.y = this->y + other.y;
return temp;
}
int main()
{
coordinate a(1, 3); //定义a类
coordinate b(2, 6); //定义b类
coordinate c; //定义c类,用来记录a+b的结果
c = a + b; //进行运算符+的重载
a.print(); //类a信息的打印
b.print(); //类b信息的打印
c.print(); //类c信息的打印
return 0;
}
C++运算符重载示例
最新推荐文章于 2024-08-17 23:59:05 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)