C++初学者:尝试将两个功能合并为一个

C++ beginner: Trying to incorporate two functions into one

本文关键字:两个 功能 合并 一个 初学者 C++      更新时间:2023-10-16

addComplex() 函数旨在接受两个 Complex 对象并返回一个 Complex 对象。返回对象的实部和虚部应该是传递给 addComplex() 的两个对象的实部和虚部之和。当然,如您所见,我只能让它返回真实部分的总和。如何在函数中包含虚部?

这是我已经工作了将近 2 个小时的家庭作业,并且正在碰壁。感谢任何正确方向的帮助。

我的代码:

#include <iostream>
#include <cmath>
using namespace std;
// class declaration section
class Complex
{
  // friends list
  friend double addComplex(Complex&, Complex&);
  private:
    double real;
    double imag;
  public:
    Complex(double = 0, double = 0);  // constructor
    void display();
 };
 // class implementation section
Complex::Complex(double rl, double im)
{
  real = rl;
  imag = im;
}
void Complex::display()
{
  char sign = '+';
  if(imag < 0) sign = '-';
  cout << real << sign << abs(imag) << 'i';
  return;
}
// friend implementations
double addComplex(Complex &a, Complex &b)
{
  return (a.real + b.real);
}
int main()
{
  Complex a(3.2, 5.6), b(1.1, -8.4);
  double num;
  cout << "The first complex number is ";
  a.display();
  cout << "nnThe second complex number is ";
  b.display();
  cout << "nnThe sum of these two complex numbers is ";
  num = addComplex(a,b);
  Complex c(num);
  c.display();

    cout << "nnThis is the end of the program.n";
    return 0;
}

您需要返回一个复杂对象,而不是双精度。

就一些代码质量提示而言,您应该创建一个常量访问器,而不是使其成为友元函数。此外,引用应该是 const 的,因为您没有修改输入。using std通常被认为是不好的做法,尽管在非头文件中还不错。

Complex addComplex(const Complex& a, const Complex& b)
{
  return Complex(a.real + b.real, a.imag + b.imag);
} 
Complex addComplex(Complex &a, Complex &b)
{
    return Complex(a.real + b.real, a.imag + b.imag);
}

您可能还需要考虑使"addComplex"函数成为"+"运算符的重载。

addComplex应该返回一个Complex对象:

Complex addComplex(const Complex &a, const Complex &b)
{
    /*Sum the real and imaginary parts, and use the constructor*/
    return Complex(a.real + b.real, a.imag + b.imag);
}

我还制作了 parmaeters const引用类型。这有助于程序稳定性,因为这意味着该函数无法修改ab