21xrx.com
2025-04-17 06:08:42 Thursday
文章检索 我的文章 写文章
C++ 实现复数类型
2023-07-03 16:10:47 深夜i     14     0
C++ 复数类型 实现

C++是一种广泛应用于各种计算机程序中的编程语言。在数学运算中,复数是一个很重要的概念,它包括实数和虚数两个部分。在C++中,我们可以使用类来实现复数类型。本文将介绍如何使用C++创建一个复数类。

为了创建一个复数类,我们需要定义两个变量来分别表示实数和虚数部分。我们可以将这两个变量定义为私有成员,并用公共函数来进行操作和计算。

下面是一个简单的复数类示例代码:

class Complex {
public:
  Complex(double real, double imaginary)
    real_ = real;
    imaginary_ = imaginary;
  
  Complex operator+ (Complex const &obj) {
    Complex res(0, 0);
    res.real_ = real_ + obj.real_;
    res.imaginary_ = imaginary_ + obj.imaginary_;
    return res;
  }
  Complex operator- (Complex const &obj) {
    Complex res(0, 0);
    res.real_ = real_ - obj.real_;
    res.imaginary_ = imaginary_ - obj.imaginary_;
    return res;
  }
  Complex operator* (Complex const &obj) {
    Complex res(0, 0);
    res.real_ = (real_ * obj.real_) - (imaginary_ * obj.imaginary_);
    res.imaginary_ = (real_ * obj.imaginary_) + (imaginary_ * obj.real_);
    return res;
  }
  void display() {
    std::cout << real_ << " + " << imaginary_ << "i" << std::endl;
  }
private:
  double real_;
  double imaginary_;
};

这个复数类实现了加减乘三种基本运算。我们可以使用上面的代码来测试这个类:

int main() {
  Complex c1(2,3);
  Complex c2(4,5);
  Complex c3 = c1 + c2;
  std::cout << "c1 + c2 = ";
  c3.display();
  Complex c4 = c1 - c2;
  std::cout << "c1 - c2 = ";
  c4.display();
  Complex c5 = c1 * c2;
  std::cout << "c1 * c2 = ";
  c5.display();
  return 0;
}

执行上面的代码将会输出以下结果:

c1 + c2 = 6 + 8i
c1 - c2 = -2 - 2i
c1 * c2 = -7 + 22i

可以看到,我们的复数类可以正确地进行加减乘运算。

除了上述的运算,我们还可以实现其他的操作,如取模(模长),求共轭数等。在实际使用中,我们可以根据需要扩展该类的功能。

总结一下,C++的类可以方便地实现复数类型,只需要在类中定义实数和虚数成员变量,并定义相应的运算操作即可。这样,我们就可以在C++程序中使用复数类型进行数学计算,提高程序的灵活性和易用性。

  
  

评论区

请求出错了