C ++初学者:尝试将两个函数合并为一个

时间:2014-03-29 22:13:39

标签: c++

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 << "\n\nThe second complex number is ";
  b.display();

  cout << "\n\nThe sum of these two complex numbers is ";

  num = addComplex(a,b);
  Complex c(num);
  c.display();



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

3 个答案:

答案 0 :(得分:0)

您需要返回Complex对象,而不是double。

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

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

答案 1 :(得分:0)

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

您可能还想考虑制作&quot; addComplex&#39;功能是&#39; +&#39;的过载。操作

答案 2 :(得分:0)

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);
}

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

相关问题