c++重载运算符==复数表示
时间: 2023-09-11 07:04:05 浏览: 51
在 C++ 中,可以通过重载运算符来定义复数的相等性比较。下面是一个示例实现:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) {
real = r;
imag = i;
}
bool operator==(const Complex& other) const {
return (real == other.real) && (imag == other.imag);
}
};
int main() {
Complex a(3.0, 4.0);
Complex b(3.0, 4.0);
Complex c(5.0, 6.0);
cout << boolalpha;
cout << (a == b) << endl; // 输出 true
cout << (a == c) << endl; // 输出 false
return 0;
}
```
在上面的示例中,我们重载了 `==` 运算符,实现了复数之间的相等性比较。注意,我们使用了常量引用作为参数,并且在函数体内使用了 `const` 修饰符,以确保不会修改被比较的对象。