Monica
Monica

Reputation: 81

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

The addComplex() function is meant to accept two Complex objects and return a Complex object. The real and imaginary parts of the returned object should be the sum of the real and imaginary parts of the two objects passed to addComplex(). Of course, as you can see, I can only get it to return the sum of the real parts. How do I include the imaginary parts within the function?

This is homework that I've been working on for almost 2 hours and am coming up against a wall. Any help in the right direction is appreciated.

My code:

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

Upvotes: 0

Views: 65

Answers (3)

Bathsheba
Bathsheba

Reputation: 234705

addComplex should return a Complex object:

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

I've also made the parmaeters const reference types. This helps program stability since it means that the function cannot modify a and b.

Upvotes: 0

user3361761
user3361761

Reputation: 259

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

You might also want to consider making the 'addComplex' function be an overload of the '+' operator.

Upvotes: 0

Antimony
Antimony

Reputation: 39451

You need to return a Complex object, not a double.

As far as some code quality tips, you should create a constant accessor instead of making it a friend function. Also, the references should be const since you aren't modifying the inputs. And using std is often considered poor practice, though it's not so bad in a non-header file.

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

Upvotes: 1

Related Questions