c++

如何用C++自定义复数类模板

小樊
84
2024-09-12 18:47:04
栏目: 编程语言

在C++中,你可以使用类模板来创建一个自定义的复数类

#include <iostream>
#include <cmath>

template <typename T>
class Complex {
public:
    // 构造函数
    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;
}

这个例子展示了如何创建一个名为Complex的类模板,它可以用于表示复数。这个类模板包含了复数的基本操作,如加法、减法、乘法和除法。在main函数中,我们创建了两个复数对象c1c2,并执行了这些操作。

0
看了该问题的人还看了