自己封装一个复数的类,参考C++自己内部的complex的模板类,要实现复数的+-*/,求模值,求角度,和实数的四则运算;
时间: 2024-11-28 10:27:31 浏览: 7
在C++中,你可以创建一个名为`Complex`的自定义类来表示复数,并实现所需的数学操作。下面是一个基本的示例,展示了如何实现复数的加减乘除、模值计算(模),以及向量对应元素的四则运算:
```cpp
#include <iostream>
#include <cmath>
template <typename T>
class Complex {
public:
// 构造函数,接受实部和虚部
Complex(T real = 0, T imag = 0)
: real_(real), imag_(imag) {}
// 获取实部和虚部
T getReal() const { return real_; }
T getImaginary() const { return imag_; }
// 设置复数的实部和虚部
void setReal(T real) { real_ = real; }
void setImaginary(T imag) { imag_ = imag; }
// 加法
Complex<T> operator+(const Complex<T>& other) const {
return Complex<T>(real_ + other.real_, imag_ + other.imag_);
}
// 减法
Complex<T> operator-(const Complex<T>& other) const {
return Complex<T>(real_ - other.real_, imag_ - other.imag_);
}
// 乘法
Complex<T> operator*(const Complex<T>& other) const {
T realProduct = real_ * other.real_ - imag_ * other.imag_;
T imagProduct = real_ * other.imag_ + imag_ * other.real_;
return Complex<T>(realProduct, imagProduct);
}
// 除法(假设除数非零)
Complex<T> operator/(const Complex<T>& other) const {
T denominatorMag = other.getMagnitude();
if (denominatorMag != T(0)) {
T realDenom = other.real_;
T imagDenom = other.imag_;
T numeratorMag = getMagnitude();
T mulReal = numeratorMag / denominatorMag;
T mulImag = imag_ * realDenom - real_ * imagDenom;
return Complex<T>(mulReal, mulImag / denominatorMag);
} else {
throw std::runtime_error("Division by zero is not allowed.");
}
}
// 求模(模长)
T magnitude() const {
return std::sqrt(real_*real_ + imag_*imag_);
}
// 求角度(弧度制)
double phase() const {
return std::atan2(imag_, real_) * (180.0 / M_PI); // 将弧度转换为度
}
private:
T real_; // 实部
T imag_; // 虚部
// 防止直接修改私有成员,提供访问器和设置器
friend std::ostream& operator<<(std::ostream& os, const Complex<T>& c);
};
// 输出复数的便利友元函数
template <typename T>
std::ostream& operator<<(std::ostream& os, const Complex<T>& complex) {
os << complex.real_ << " + " << complex.imag_ << "i";
return os;
}
int main() {
Complex<int> a(3, 4);
Complex<int> b(1, 2);
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
Complex<int> sum = a + b;
std::cout << "Sum: " << sum << "\n";
Complex<int> diff = a - b;
std::cout << "Difference: " << diff << "\n";
Complex<int> product = a * b;
std::cout << "Product: " << product << "\n";
Complex<int> quotient = a / b;
std::cout << "Quotient: " << quotient << "\n";
std::cout << "Magnitude of a: " << a.magnitude() << "\n";
std::cout << "Angle of a: " << a.phase() << " degrees\n";
return 0;
}
```
这个例子中,`Complex`类模板允许你使用任何浮点类型的复数(如`float`, `double`, 或自定义的`T`)。运行上述代码,你会看到一个简单的复数运算实例。
阅读全文