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

1949idc 2年前 (2024-09-18) 阅读数 290 #编程语言

在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,并执行了这些操作。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业