编写一个复数类模板complex,其数据成员real和image
时间: 2024-03-01 15:53:46 浏览: 22
好的,下面是一个简单的复数类模板complex的实现:
```cpp
template<typename T>
class complex {
public:
T real;
T image;
complex(T r = 0, T i = 0) : real(r), image(i) {}
complex<T> operator+(const complex<T>& other) const {
return complex<T>(real + other.real, image + other.image);
}
complex<T> operator-(const complex<T>& other) const {
return complex<T>(real - other.real, image - other.image);
}
complex<T> operator*(const complex<T>& other) const {
return complex<T>(real * other.real - image * other.image, real * other.image + image * other.real);
}
complex<T> operator/(const complex<T>& other) const {
T denominator = other.real * other.real + other.image * other.image;
return complex<T>((real * other.real + image * other.image) / denominator, (image * other.real - real * other.image) / denominator);
}
bool operator==(const complex<T>& other) const {
return (real == other.real) && (image == other.image);
}
bool operator!=(const complex<T>& other) const {
return !(*this == other);
}
friend std::ostream& operator<<(std::ostream& os, const complex<T>& c) {
os << c.real << "+" << c.image << "i";
return os;
}
};
```
这个类模板定义了一个复数类,包含实部和虚部两个数据成员。它的构造函数可以接受两个参数,分别是实部和虚部的值。同时,它还重载了加、减、乘、除、相等和不相等操作符,以及输出操作符。