1:重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。
如:
Box operator+(const Box&);
2:需要注意的点
2.1重载运算符函数的参数个数,应该与参与这个运算符的运算对象数量一样多,但是如果是成员函数,则参数数量要少一个,因为第一个参数是this。
2.2运算符重载函数的参数至少要有一个类的成员(或者类类型)作为参数,而不能都是内置类型(会导致编译错误)。例如int operator+(int, int)是不行的,因为int是内置类型。内置类型的操作符明显是不能重载的,比如重载了int型的+运算符,那程序其他地方的int加法都会使用重载的函数,这明显是不行的。
2.3运算符可以像普通函数一样调用。例如下面例子的a+b等同于a.operator+(b);。
2.4不应该重载的运算符(当然理论是可以重载的,只是重载之后容易出问题):逗号、&、&&、||。
2.5必须作为成员函数的重载运算符:=、[]、()、->,否则会编译错误。
2.6重载运算符函数是成员函数时,其实就是运算符左侧的对象调用的这个运算符,所以左侧对象必须是运算符所属类的一个对象(这个是当然的,因为第一个参数是这个类的this指针)。
3:example.cpp
#include <iostream>
using namespace std;
class Box{
private:
int a;
int b;
int c;
public:
Box(int a, int b, int c) {
this->a = a;
this->b = b;
this->c = c;
}
Box() {}
// Box operator+(Box &box) {
// Box temp;
// temp.a = this->a + box.a;
// temp.b = this->b + box.b;
// temp.c = this->c + box.c;
// return temp;
// }
friend Box operator+(Box &box1, Box &box2);
int volume() {
return a * b * c;
}
};
// this cannot work for the 'a,b,c' is private within this context
// type their set/get function can work
// or announce this function as friend
Box operator+(Box &box1, Box &box2) {
Box temp;
temp.a = box1.a + box2.a;
temp.b = box1.b + box2.b;
temp.c = box1.c + box2.c;
return temp;
}
int main() {
Box *box = new Box(1,2,3);
int a = box->volume();
cout<<a<<endl;
a = (*box).volume();
cout<<a<<endl;
delete box;
Box b1(1,2,3);
Box b2(1,2,3);
Box temp;
temp = b1 + b2;
cout<<temp.volume()<<endl;
}