在C++中,你可以使用類模板來創(chuàng)建一個自定義的復數(shù)類
#include <iostream>
#include <cmath>
template <typename T>
class Complex {
public:
// 構造函數(shù)
Complex(T real, T imag) : real_(real), imag_(imag) {}
// 獲取實部和虛部
T real() const { return real_; }
T imag() const { return 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 real_part = real_ * other.real_ - imag_ * other.imag_;
T imag_part = real_ * other.imag_ + imag_ * other.real_;
return Complex<T>(real_part, imag_part);
}
// 除法
Complex<T> operator/(const Complex<T>& 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<T>(real_part, imag_part);
}
private:
T real_;
T imag_;
};
int main() {
Complex<double> c1(3, 4);
Complex<double> c2(1, 2);
Complex<double> sum = c1 + c2;
Complex<double> diff = c1 - c2;
Complex<double> prod = c1 * c2;
Complex<double> 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;
}
這個例子展示了如何創(chuàng)建一個名為Complex
的類模板,它可以用于表示復數(shù)。這個類模板包含了復數(shù)的基本操作,如加法、減法、乘法和除法。在main
函數(shù)中,我們創(chuàng)建了兩個復數(shù)對象c1
和c2
,并執(zhí)行了這些操作。