亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何用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
芜湖县| 兴业县| 肃宁县| 临桂县| 都匀市| 龙州县| 铜山县| 军事| 东源县| 大荔县| 威海市| 天镇县| 临沧市| 闸北区| 百色市| 千阳县| 喀喇| 常熟市| 青岛市| 嘉峪关市| 宿松县| 宜宾县| 富平县| 奇台县| 旅游| 贡山| 基隆市| 子洲县| 武冈市| 龙川县| 黑河市| 克什克腾旗| 黄龙县| 大方县| 广饶县| 临潭县| 永州市| 河间市| 上思县| 东城区| 遂川县|