实现一个CComplex class(数学里的复数),练习运算符的重载。 要求具有以下操作: ①构造函数 ②拷贝构造函数 ③operator= ④operator* ⑤operator+ ⑥operator- ⑦operator/ ⑧operator== ⑨operator[] ⑩operator!= 其中,复数类的实部和虚部的取值类型为float。
时间: 2023-09-05 12:11:00 浏览: 83
以下是一个可能的实现:
```cpp
#include <iostream>
class CComplex {
public:
CComplex(float r = 0, float i = 0) : real(r), imag(i) {}
CComplex(const CComplex& other) : real(other.real), imag(other.imag) {}
CComplex& operator=(const CComplex& other) {
real = other.real;
imag = other.imag;
return *this;
}
CComplex operator*(const CComplex& other) const {
return CComplex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
CComplex operator+(const CComplex& other) const {
return CComplex(real + other.real, imag + other.imag);
}
CComplex operator-(const CComplex& other) const {
return CComplex(real - other.real, imag - other.imag);
}
CComplex operator/(const CComplex& other) const {
float denominator = other.real * other.real + other.imag * other.imag;
return CComplex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator);
}
bool operator==(const CComplex& other) const {
return real == other.real && imag == other.imag;
}
float operator[](int index) const {
if (index == 0) {
return real;
} else if (index == 1) {
return imag;
} else {
std::cerr << "Invalid index" << std::endl;
return 0;
}
}
bool operator!=(const CComplex& other) const {
return !(*this == other);
}
friend std::ostream& operator<<(std::ostream& os, const CComplex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
private:
float real;
float imag;
};
int main() {
CComplex c1(1, 2), c2(3, 4);
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
CComplex c3 = c1 + c2;
std::cout << "c3 = " << c3 << std::endl;
CComplex c4 = c1 - c2;
std::cout << "c4 = " << c4 << std::endl;
CComplex c5 = c1 * c2;
std::cout << "c5 = " << c5 << std::endl;
CComplex c6 = c1 / c2;
std::cout << "c6 = " << c6 << std::endl;
std::cout << "c1[0] = " << c1[0] << std::endl;
std::cout << "c1[1] = " << c1[1] << std::endl;
std::cout << "c1 == c2? " << (c1 == c2) << std::endl;
std::cout << "c1 != c2? " << (c1 != c2) << std::endl;
return 0;
}
```
在这个实现中,我们定义了一个`CComplex`类,它具有一个实部和一个虚部,它们的取值类型为`float`。我们重载了运算符`+`、`-`、`*`、`/`、`=`、`[]`、`==`和`!=`来实现复数的基本运算和比较。我们还定义了构造函数和拷贝构造函数来创建和复制复数对象。最后,我们定义了一个友元函数`operator<<`,以便我们可以使用`std::cout`来打印复数对象。
阅读全文