简体   繁体   中英

How to overload == operator without making it a friend function?

I have a class SomeClass and I wish to implement an overloaded == to compare two instances of this class.

The overloaded == does not make use of any of SomeClass 's private members. So, it does not have to be a friend .

How do I make it a non-member, non-friend function?

Currently, this is what my code looks like:

someclass.h

#ifndef SOMECLASS_H
#define SOMECLASS_H

class SomeClass
{
public:
    // Other class declarations, constructors
    friend bool operator==(const SomeClass a, const SomeClass b);
};

someclass.cpp

#include "someclass.h"

// Other stuff 

bool operator==(const SomeClass a, const SomeClass b) {
// do some comparison and return true/false
}

Like @HolyBlackCat pointed out, you can provide the operator== overload as a free function. It will be a free-function, meaning you can either write

#ifndef SOMECLASS_H
#define SOMECLASS_H

// namespaces if any

class SomeClass
{
    // Other class declarations, constructors
};

bool operator==(const SomeClass& a, const SomeClass& b) noexcept
{
    // definition
}

// end of namespaces if any!

#endif  // end of SOMECLASS_H

or

declare operator== in the header and provide the definition of the free function in the corresponding cpp file

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