一、什么是操作符重载
操作符重载可以分为两部分:“操作符”和“重载”。说到重载想必都不陌生了吧,这是一种编译时多态,重载实际上可以分为函数重载和操作符重载。运算符重载和函数重载的不同之处在于操作符重载重载的一定是操作符。我们不妨先直观的看一下所谓的操作符重载:
#include <iostream>
using namespace std;
int main()
{
int a = 2 , b = 3;
float c = 2.1f , d = 1.2f;
cout<<"a + b = "<<a+b<<endl;
cout<<"c + d = "<<c+d<<endl;
return 0;
}
我们看到操作符“+”完成float和int两种类型的加法计算,这就是操作符重载了。这些内置类型的操作符重载已经实现过了,但是如果现在我们自己写过的类也要实现实现类似的加法运算,怎么办呢??比如现在现在有这样一个点类point,要实现两个点的相加,结果是横纵坐标都要相加,这时候就需要我们自己写一个操作符重载函数了。
#include <iostream> using namespace std; class point { double x; double y; public: double get_x() { return x; } double get_y() { return y; } point(double X = 0.0 , double Y = 0.0):x(X),y(Y){}; point operator +(point p); }; //重载操作符“+” point point::operator +(point p) { double x = this->x + p.x; double y = this->y + p.y; point tmp_p(x,y); return tmp_p; } int main() { point p1(1.2,3.1); point p2(1.1,3.2); point p3 = p1+p2; cout<<p3.get_x()<<" "<<p3.get_y()<<endl; return 0; } |