-2

I was trying normal friend function. And I got stuck at this point. It is showing that class Complexnos has no member add.

#include<iostream>
using namespace std;

class Complexnos
{
    private:
    int real,img;
    public:
    void read()
    {
        cout<<"Enter the Real and Imaginary numbers : ";
        cin>>real>>img;    
    }

    friend Complexnos add(Complexnos c1, Complexnos c2);
    
    void display()
    {
        cout<<"The addition of the Complex numbers is : "<<real<<" + "<<img<<"i";
    }

};

Complexnos add(Complexnos c1, Complexnos c2)
{
    Complexnos c;
    c.real = c1.real + c2.real;
    c.img = c2.img + c2.img;
    return c;
}
int main()
{
    Complexnos c1;
    Complexnos c2;
    Complexnos c3;
    c1.read();
    c2.read();
    c3 = c1.add(c1,c2); <-- Having error here! 
    c3.display();
    return 0;
}

This code is adding 2 complex number using friend function

Pratham Yadav
  • 31
  • 1
  • 7

1 Answers1

1

Your line below declares a free function that takes two parameters.

friend Complexnos add(Complexnos c1, Complexnos c2);

But your usage here assumes a non-free member function, taking one parameter.

c3 = c1.add(c2); <-- Having error here! 

If you are genuinely attempting a friend function use:

add( c1, c2 );
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180