操作符重载

来源:互联网 发布:加工中心编程学徒招聘 编辑:程序博客网 时间:2024/05/22 13:37

这里是借鉴他人的结论在此学习,拓展,后面会继续修改完善

//操作符实现重载的方式有两种,一种是“友元函数”,一种是“类成员函数”

//类成员函数只有一个参数,因为类成员函数可以使用this指针获取自身的对象
#include <iostream>
using namespace std;


class Point
{
public:
int x;
int y;
Point(int _x, int _y) :x(_x), y(_y)
{


}
Point operator+(Point &p)//实现坐标向量加
{
int t1 = this->x + p.x;//this指针指向的x加上对象p的x值
int t2 = this->y + p.y;
Point t(t1, t2);
return t;
}
friend int operator*(Point &p1, Point &p2);//实现内积
};


int operator*(Point &p1, Point &p2)
{
return (p1.x*p2.x) + (p1.y*p2.y);
}


int main()
{
Point p1(1, 4);
Point p2(3, 5);
cout << p1*p2 << endl;//输出内积1*3+4*5=23


Point p3=p1+p2;
cout << "p3:(" << p3.x << "," << p3.y << ")" << endl; //(4,9)
system("pause");
return 0;
}
原创粉丝点击