91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何用C++自定義復數類模板

c++
小樊
83
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
浪卡子县| 上犹县| 凉山| 巴林右旗| 伊吾县| 肥乡县| 得荣县| 确山县| 来凤县| 军事| 桐柏县| 普洱| 北流市| 宁强县| 马鞍山市| 尼玛县| 玉田县| 随州市| 林周县| 会泽县| 福贡县| 理塘县| 定边县| 新沂市| 手游| 乡宁县| SHOW| 钦州市| 宁海县| 香河县| 甘孜县| 嘉荫县| 延安市| 常德市| 台北县| 理塘县| 高雄市| 慈利县| 丰原市| 淮北市| 乐昌市|