Error while adding Complex numbers

In below program I am getting 2 errors at below lines.
1. r = sum(p,q); //Function sum should have a prototype.
2. r = sum(p,q); //Cannot convert int to complex

Kindly advise the changes in the code.

Note: I have to do the code by passing objects of complex class to add and also the addition should return a complex number.

#include<iostream.h>
#include<conio.h>

class Complex
{
private:
int real;
int imag;

public:
void getNo()
{
cout<<"Enter real part : "<<endl;
cin>>real;
cout<<"Enter imaginary part : "<<endl;
cin>>imag;
}

void showNo()
{
cout<<real<<"+"<<imag<<"i";
}

Complex sum(Complex, Complex);
};

Complex Complex :: sum(Complex c1, Complex c2)
{
Complex a;
a.real = c1.real + c2.real;
a.imag = c1.imag + c2.imag;
return a;
}

void main()
{
clrscr();
Complex p,q,r,s;
p.getNo();
q.getNo();
cout<<endl<<"First complex number is : ";
p.showNo();

cout<<endl<<"Second complex number is : ";
q.showNo();

r = sum(p,q);
cout<<"Addtion of the complex no is : ";
r.showNo();

getch();
}
Right now, you have a sum as a member function ("method") of class Complex. That means that the function needs to be called through an object of type Complex.

1
2
3
4
Complex p, q, r;
Complex my_complex_obj;

Complex r = my_complex_obj.sum(p, q);


This would solve your problem, but this isn't really an intuitive way to use your sum function, because the my_complex object isn't actually being used in sum.

My preferred workaround would be to make sum be a non-member, friend function of Complex.

Declaring a function as a friend of a class lets that function use the class objects' private members.
http://en.cppreference.com/w/cpp/language/friend

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
class Complex
{
   // ...

    friend Complex sum(Complex, Complex);
};

Complex sum(Complex c1, Complex c2)
{
    Complex a;
    a.real = c1.real + c2.real;
    a.imag = c1.imag + c2.imag;
    return a;
}

// ...
int main()
{
    Complex p, q;
    p.getNo();
    q.getNo();

    Complex r = sum(p, q);

    return 0;
}


Last edited on
Topic archived. No new replies allowed.