溫馨提示×

如何用C++自定義復數(shù)類模板

c++
小樊
83
2024-09-12 18:47:04
欄目: 編程語言

在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ù)對象c1c2,并執(zhí)行了這些操作。

0