为复数类增加重载的运算符
时间: 2023-06-22 08:48:31 浏览: 94
为了为复数类增加重载的运算符,我们可以使用C++中的运算符重载。其中,我们可以重载加号、减号、乘号、除号、等号、小于号、大于号等运算符。
下面是一个复数类的例子,其中包括加法、减法、乘法和除法的运算符重载:
```c++
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) const;
Complex operator-(const Complex& c) const;
Complex operator*(const Complex& c) const;
Complex operator/(const Complex& c) const;
bool operator<(const Complex& c) const;
bool operator>(const Complex& c) const;
bool operator==(const Complex& c) const;
Complex& operator=(const Complex& c);
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex Complex::operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex Complex::operator*(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex Complex::operator/(const Complex& c) const {
double den = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / den, (imag * c.real - real * c.imag) / den);
}
bool Complex::operator<(const Complex& c) const {
return real < c.real;
}
bool Complex::operator>(const Complex& c) const {
return real > c.real;
}
bool Complex::operator==(const Complex& c) const {
return (real == c.real) && (imag == c.imag);
}
Complex& Complex::operator=(const Complex& c) {
real = c.real;
imag = c.imag;
return *this;
}
int main() {
Complex a(1, 2);
Complex b(3, 4);
Complex c = a + b;
Complex d = a - b;
Complex e = a * b;
Complex f = a / b;
if (a < b)
cout << "a < b" << endl;
else if (a > b)
cout << "a > b" << endl;
else
cout << "a == b" << endl;
return 0;
}
```
在上面的例子中,我们定义了一个名为Complex的类,它有两个数据成员:实部和虚部。我们重载了加法、减法、乘法、除法、小于号、大于号和等于号等运算符。这些运算符的重载使我们可以像使用内置类型一样使用Complex类。