Friend Function = Operator Overloading of two different class

I am practicing operator overloading , i have done hundred times operator overloading but this time it's behavior is irritating if I compare this code with old code syntax (that complies fine) i find no change in syntax ,kindly guide me.Thanks

EROR : [Error] 'two operator=(one, two)' must be a nonstatic member function

#include<iostream>
using namespace std;
class two;
class one{
    int sno;
    public:
        one()
        {
            sno=312;
        }

    friend two operator =(one,two);
};  
    //b b1; b1=a.seatno;
class two{
    int seatno;
    public:
        two(){seatno=0;
        }
        friend two operator = (one,two);

};

    two operator = (one a1,two b1)
    {
        b1.seatno=a1.sno;
        return b1;
    }
int main()
{
    one a1;
    two b1;
    b1=a1;
}

[Error] 'two operator=(one, two)' must be a nonstatic member function

Upvotes: 2

Views: 444

Answers (1)

bruno
bruno

Reputation: 32586

You want that :

#include<iostream>
using namespace std;

class two;

class one{
    int sno;
  public:
    one() : sno(312) {}
    //one & operator =(const two & t);
    int getSno() const { return sno; }
};  

class two{
    int seatno;
  public:
    two() : seatno(0) {}
    two & operator = (const one & o);
    int getSeatno() const { return seatno; }
};

two & two::operator =(const one & o)
{
  seatno = o.getSno();
  return *this;
}

int main()
{
  one a1;
  two b1;

  cout << b1.getSeatno() << endl;
  b1=a1;
  cout << b1.getSeatno() << endl;
}

For the type T the signature of the operator= is T & operator(const TT &); where TT can be T.

The operator= as some others cannot be a non-member, see https://en.cppreference.com/w/cpp/language/operators.

Note also to a getter is needed to get the value of the non public attributes seatno and sno

Compilation and execution :

/tmp % g++ -pedantic -Wall -Wextra a.cc
/tmp % ./a.out
0
312

Upvotes: 2

Related Questions