不同的操作符有不同的用途,因此在重载时需要根据其作用进行不同的实现。下面示例重载了 "+" 和 "-" 操作符:
#include
using namespace std;
class Complex{
private:
double real,imag;
public:
Complex(double r = 0, double i = 0):real(r),imag(i){ }
Complex operator+(Complex const &obj){
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Complex operator-(Complex const &obj){
Complex res;
res.real = real - obj.real;
res.imag = imag - obj.imag;
return res;
}
void print(){
cout << real << " + i" << imag << endl;
}
};
int main(){
Complex c1(3, 5), c2(2, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
c3.print();
c4.print();
return 0;
}
在上面的示例中,Complex 类中写了 + 和 - 两个操作符的重载函数,因为这两个操作符的含义是不同的。在 main 函数中通过调用对象的操作符重载函数计算,并打印结果。由此可见,不同操作符的重载方法是不同的,需要根据其作用进行不同的实现。