定义一个复数类 Complex,重载运算符“+”、“-”、“*”、“~” “==”以及“<<”,使之能用于复数的加、减、乘、求反(虚部反)、比较和输出等运算。 其中“+”“-”“~”重载为成员函数,“*”“==”“<<”重载为友元函数。
时间: 2023-10-01 20:09:59 浏览: 267
定义复数类Complex,进行运算符重载
5星 · 资源好评率100%
好的,以下是 Complex 类的定义及相关运算符重载的实现:
```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;
}
// 重载加法运算符
Complex operator +(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
// 重载减法运算符
Complex operator -(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
// 重载乘法运算符
Complex operator *(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
// 重载求反运算符
Complex operator ~() const {
return Complex(real, -imag);
}
// 重载相等运算符
bool operator ==(const Complex& c) const {
return (real == c.real) && (imag == c.imag);
}
// 友元函数,重载输出运算符
friend ostream& operator <<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << "i)";
return os;
}
};
int main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2;
Complex c4 = c2 - c1;
Complex c5 = c1 * c2;
Complex c6 = ~c1;
bool b1 = (c1 == c2);
bool b2 = (c1 == Complex(1, 2));
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
cout << "c1 + c2 = " << c3 << endl;
cout << "c2 - c1 = " << c4 << endl;
cout << "c1 * c2 = " << c5 << endl;
cout << "~c1 = " << c6 << endl;
cout << "c1 == c2: " << b1 << endl;
cout << "c1 == Complex(1, 2): " << b2 << endl;
return 0;
}
```
运行结果:
```
c1 = (1, 2i)
c2 = (3, 4i)
c1 + c2 = (4, 6i)
c2 - c1 = (2, 2i)
c1 * c2 = (-5, 10i)
~c1 = (1, -2i)
c1 == c2: 0
c1 == Complex(1, 2): 1
```
阅读全文