21xrx.com
2025-04-13 09:21:30 Sunday
文章检索 我的文章 写文章
C++实现复数类的加减运算
2023-07-04 17:41:59 深夜i     13     0
C++ 复数类 加减运算

复数是数学中的一种数,有实部和虚部。在编程中,为了方便计算和操作,我们需要定义一个复数类。本文将介绍在C++中如何实现复数类的加减运算。

首先,我们需要定义一个复数类。复数类需要包括实部和虚部两个成员变量,以及构造函数、赋值运算符、加法运算符、减法运算符等成员函数。以下是复数类的基本定义:

class Complex {
public:
  Complex(double real = 0, double imag = 0);
  Complex& operator=(const Complex& other);
  Complex operator+(const Complex& other) const;
  Complex operator-(const Complex& other) const;
  double real() const return _real;
  double imag() const return _imag;
private:
  double _real;
  double _imag;
};

其中,构造函数用于初始化实部和虚部;赋值运算符用于将一个复数对象赋值给另一个复数对象;加法运算符和减法运算符用于实现复数的加减运算。

接下来是成员函数的具体实现。构造函数的定义如下:

Complex::Complex(double real, double imag) : _real(real), _imag(imag) {}

赋值运算符的定义如下:

Complex& Complex::operator=(const Complex& other) {
  if (this != &other)
    _real = other._real;
    _imag = other._imag;
  
  return *this;
}

加法运算符和减法运算符的定义如下:

Complex Complex::operator+(const Complex& other) const {
  return Complex(_real + other._real, _imag + other._imag);
}
Complex Complex::operator-(const Complex& other) const {
  return Complex(_real - other._real, _imag - other._imag);
}

以上代码实现了复数类的加减运算。我们可以通过以下方式进行测试:

int main() {
  Complex c1(1, 2);
  Complex c2(3, 4);
  Complex c3 = c1 + c2;
  Complex c4 = c1 - c2;
  cout << c3.real() << " + " << c3.imag() << "i" << endl;
  cout << c4.real() << " + " << c4.imag() << "i" << endl;
  return 0;
}

输出结果为:

4 + 6i
-2 + -2i

通过上述测试结果可以看出,复数类的加减运算已经成功实现。

总结来说,通过上述代码可以看出,在C++中实现复数类的加减运算并不难,只需要定义一个复数类,并实现其成员函数即可。通过这种方法,我们可以在编程中方便地处理复数运算。

  
  

评论区

请求出错了