简体   繁体   中英

possible implementations of casting in c++

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

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);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM