21xrx.com
2025-03-27 10:17:45 Thursday
文章检索 我的文章 写文章
C++复数加法函数
2023-07-05 04:04:38 深夜i     14     0
C++ 复数 加法函数

在C++中,我们可以使用类来实现复数的加法。下面是一个简单的示例:

#include <iostream>
using namespace std;
class Complex {
public:
  double real;
  double imag;
  Complex(double x, double y)
    real = x;
    imag = y;
  
  Complex operator+(Complex const &obj) {
    return Complex(real + obj.real, imag + obj.imag);
  }
};
int main() {
  Complex c1(2, 3);
  Complex c2(4, 5);
  Complex c3 = c1 + c2;
  cout << c3.real << " + " << c3.imag << "i" << endl;
  return 0;
}

这里定义了一个`Complex`类,其中包含了实部和虚部两个成员变量。我们通过构造方法来初始化这两个成员变量。`operator+`函数重载了加号操作符,用来实现复数的加法。

在`main`函数中,我们定义了两个复数`c1`和`c2`,将它们相加得到复数`c3`,然后输出其实部和虚部。

这个示例只是实现了最基本的复数加法,要实现更多的复数运算还需要在类中添加相应的成员函数。

  
  

评论区