Passing a class into its own member function

Hello. I have a problem with coding the add_complex. How do I get the x values to sum with the y values?

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include "Complex.h"

using namespace std;

int main()
{
    Complex x,y,z;

    x.setdata(1.2,2.3);  //set x as 1.2 + 2.3i
    y.setdata(3.4,4.5);  //set y as 3.4 + 4.5i

    //print out the value of x
    cout << "The value of x is: ";
    x.print_complex();
    cout << endl;

    //print out the value of y
    cout << "The value of y is: ";
    y.print_complex();
    cout << endl;

    //add y and x, i.e., z = x+y)
    z = x.add_complex(y);
    //print out the value of x
    cout << "The sum of x and y is: ";

    z.print_complex();
    cout << endl;

}


complex.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Declare the class Complex

using namespace std;

class Complex
{
  private:
    double a,b;       //this complex number is a+bi
  public:
    void setdata(double, double); // this function sets the values of a and b (the first parameter is set as a; the second is set as b)
    double get_real();  // return the value of a;
    double get_imag();  // return the value of b;
    void print_complex();           // when this function is called, print out the value: a+bi
    Complex add_complex(Complex);   // addition of two complex numbers, return the sum
};





Complex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include "Complex.h"

void Complex::setdata(double a1, double b1) {
    a=a1;
    b=b1;
}

double Complex::get_real(){
    return a;
}

double Complex::get_imag(){
    return b;
}

void Complex::print_complex(){
    cout<<a<<"+"<<b<<"i";
}

Complex add_complex(Complex& y){
    += y.get_real();
    += y.get_imag();
}
1
2
3
4
Complex Complex::add_complex(const Complex& y)
{
   return Complex(a + y.a, b + y.b);
}


If you want to make this really nice, you could overload the addition operator:
1
2
3
4
5
6
7
8
9
10
11
friend Complex operator+(const Complex& lhs, const Complex& rhs)
{
    return Complex(lhs.a + rhs.a, lhs.b + rhs.b);
}

// Usage
auto a = Complex(1.0, 2.0);
auto b = Complex(3.0, 4.0);
auto c = a + b;

c.print_complex();










4.0 + 6.0i
Last edited on
complex.cpp lines 22-23: What do these lines do? You have no left hand side to assign the values to.
Topic archived. No new replies allowed.