tags:

views:

100

answers:

3

I have this snippet of the code in my header:

class A {
private:
    int player;
public:
    A(int initPlayer = 0);
    A(const A&);
    A& operator=(const A&);
    ~A();
    void foo() const;
friend int operator==(const A& i, const A& member) const;
};

implementation of the operator==

int operator==(const A& i, const A& member) const{
    if(i.player == member.player){
        return  1;
    }
    return 0;

}

and I need casting for this part of my code:

i - is some int, which my function receives

A *pa1 = new A(a2);

assert(i == *pa1);

I receive an error non-member function, How can I fix it? thanks in advance

+3  A: 

Your error is nothing to do with casting or user-defined conversions.

You can't have a const qualification on a function that isn't a member function so this:

int operator==(const A& i, const A& member) const;

should be this:

int operator==(const A& i, const A& member);
Charles Bailey
+1  A: 

Remove the const qualifier from the friend function. Friend functions are not member functions hence the const qualifier is meaningless.

sashang
A: 

There are two solutions:

  1. Make operator==() a member function, not a friend:

    Interface:

    class A {
    private:
        int player;
    public:
        A(int initPlayer = 0);
        A(const A&);
        A& operator=(const A&);
        ~A();
        void foo() const;
        int operator==(const A& rhv) const;
    };
    

    Implementation:

    int A::operator==(const A& rhv) const
    {
        return this->player == rhv.player;
    }
    
  2. If you really want operator==() as a friend function, just remove the const qualifier, as mentioned in the other posts.

slaimi