问题描述
我有一个SomeClass
类,我想实现一个重载的==
来比较该类的两个实例。
重载的==
不使用SomeClass
的任何私有成员。因此,它不必是friend
。
如何使其成为非成员,非朋友功能?
当前,这是我的代码:
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
}
解决方法
就像 @HolyBlackCat 指出的那样,您可以提供operator==
重载作为自由函数。这将是一个免费功能,这意味着您可以编写
#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
或
在标头中声明operator==
,并在相应的cpp文件中提供自由功能的定义