在C++中,operator
是一个关键字,用于定义和重载运算符。运算符重载是C++的一个强大特性,允许你重新定义内置的运算符,以便它们适用于自定义的数据类型或类对象。最后return是你运算完之后返回的值。
重载加法(二元)运算符:
class Point {
private:
int x;
int y;
public:
Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {} //构造函数
Point operator+(const Point& other) { //因为是二元运算符、所以这里
return Point(x + other.x, y + other.y);
}
};
int main(){
Point p1(2, 3);
Point p2(4, 5);
Point result = p1 + p2;
}
重载一元运算符
class Counter {
private:
int count;
public:
Counter(int initialCount) : count(initialCount) {}
Counter operator++() {
++count;
return *this;
}
};
int main(){
Counter c(5);
++c;
}
重载()括号:
class person{
public:
person(int a,int b){
printf("%d\n",a+b);
}
void operator()(int a,int b){
printf("%d\n",a+2*b);
}
};
int main()
{
person p(1,2);
p(1,3);
return 0;
}
可以看到在声明函数的时候的括号并不会触发operator。