在C++中,你可以使用类模板来创建一个自定义的复数类
#include
#include
template
class Complex {
public:
// 构造函数
Complex(T real, T imag) : real_(real), imag_(imag) {}
// 获取实部和虚部
T real() const { return real_; }
T imag() const { return imag_; }
// 加法
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
// 减法
Complex operator-(const Complex& other) const {
return Complex(real_ - other.real_, imag_ - other.imag_);
}
// 乘法
Complex operator*(const Complex& other) const {
T real_part = real_ * other.real_ - imag_ * other.imag_;
T imag_part = real_ * other.imag_ + imag_ * other.real_;
return Complex(real_part, imag_part);
}
// 除法
Complex operator/(const Complex& other) const {
T denominator = other.real_ * other.real_ + other.imag_ * other.imag_;
T real_part = (real_ * other.real_ + imag_ * other.imag_) / denominator;
T imag_part = (imag_ * other.real_ - real_ * other.imag_) / denominator;
return Complex(real_part, imag_part);
}
private:
T real_;
T imag_;
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex sum = c1 + c2;
Complex diff = c1 - c2;
Complex prod = c1 * c2;
Complex quot = c1 / c2;
std::cout << "Sum: " << sum.real() << " + " << sum.imag() << "i\n";
std::cout << "Difference: " << diff.real() << " + " << diff.imag() << "i\n";
std::cout << "Product: " << prod.real() << " + " << prod.imag() << "i\n";
std::cout << "Quotient: " << quot.real() << " + " << quot.imag() << "i\n";
return 0;
}
这个例子展示了如何创建一个名为Complex
的类模板,它可以用于表示复数。这个类模板包含了复数的基本操作,如加法、减法、乘法和除法。在main
函数中,我们创建了两个复数对象c1
和c2
,并执行了这些操作。