运算符重载 class+Fraction+0 int+fenzi;|+//分子 int+fenmu;/+/1分母 public: Fraction+operator+=+(const+Fraction
时间: 2023-12-14 21:32:33 浏览: 127
运算符重载
运算符重载是指在类中定义某些运算符的行为,使得该类的对象可以像基本数据类型一样进行运算。在C++中,可以通过重载运算符来实现运算符重载。运算符重载必须在类中进行申明和定义,且必须传参类型为‘类’。常见的运算符重载包括加减乘除、赋值、比较等。
以下是一个运算符重载的例子:
```c++
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int 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;
}
};
int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // 调用运算符重载:+
Complex c4 = c1 - c2; // 调用运算符重载:-
return 0;
}
```
阅读全文