1
#include<iostream>
using namespace std;
class a
{
    int x;
    int y;
    public:
    void get_xy(int x,int y)
    {
        this->x=x;
        this->y=y;  
    }   
    friend int operator=(a,a);
};
int operator=(a a5,a a6)
{
    if(a5.x==a6.x&&a5.y==a6.y)
    {
        return(1);
    }
    else
    {
        return 0;
    }
}

int main()
{
    a a1,a2;
    a1.get_xy(5,4);
    a2.get_xy(5,4);
    if(a1=a2)
    {
        cout<<"y"<<endl;
    }
    else
    {
        cout<<"n"<<endl;
    }

    return 0;
}

I am trying to overload the assignment operator= by means of using a friend function and stuck with error in attached screen shot. However when I overload it with a member function it works as expected. The code is posted above.

jhoepken
  • 1,842
  • 3
  • 17
  • 24
Meet Shah
  • 15
  • 4
  • 7
    The assignment operator can't be made a non-member function, it must *always* be a member function. See the table in [this operator overloading reference](http://en.cppreference.com/w/cpp/language/operators). – Some programmer dude Mar 06 '16 at 10:17
  • Please reconsider your use of bad practices [`using namespace std;`](http://stackoverflow.com/q/1452721/1171191) and [`endl`](http://chris-sharpe.blogspot.co.uk/2016/02/why-you-shouldnt-use-stdendl.html). – BoBTFish Mar 06 '16 at 10:22
  • 2
    Overloading `operator=` to mean `==` would be **extremely** confusing for everyone else. Also your `get_xy` looks very much like a `set_xy` function, or better could be a constructor for `a`. – Bo Persson Mar 06 '16 at 11:14
  • I admire your code obfuscation skills. – Sebastian Redl Mar 15 '16 at 16:15

1 Answers1

0

C++11 13.5.3/1:

An assignment operator shall be implemented by a non-static member function with exactly one parameter...

So the standard just flatly prohibits overloading operator= as a non-member.

And as a side note: Don't overload assignment to mean comparison, it will confuse all future maintainers.

Mark B
  • 95,107
  • 10
  • 109
  • 188