mah*_*ood 4 c++ operator-overloading
我已经定义了一个这样的类
using namespace std;
class foo {
public:
typedef std::pair< int, int > index;
bool operator == ( const index &l, const index &r )
{
return (l.first == r.first && l.second == r.second);
}
void bar()
{
index i1;
i1.first = 10;
i1.second = 20;
index i2;
i2.first = 10;
i2.second = 200;
if (i1 == i2)
cout << "equal\n";
}
};
Run Code Online (Sandbox Code Playgroud)
但是我在 Windows 中收到此错误
error C2804: binary 'operator ==' has too many parameters
Run Code Online (Sandbox Code Playgroud)
而这个错误在 linux 中
operator==(const std::pair<int, int>&, const std::pair<int, int>&)’ must take exactly one argument
Run Code Online (Sandbox Code Playgroud)
我发现这个主题重载 operator== 抱怨“必须只采用一个参数”,并且似乎是类中静态和非静态函数的问题。但是不知道怎么申请this
例如,这是不正确的
bool operator == ( const index &r )
{
return (this->first == r.first && this->second == r.second);
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
该operator==
可以通过两种方式实现:
this
指针隐式传递给函数。由于您正在实现operator==
for std::pair
,因此您不能将其实现为成员函数( of std::pair
)。剩下的选项是非成员函数。
所以在类外实现它:
bool operator==(std::pair<int,int> const & l, std::pair<int,int> const & r)
{
return (l.first == r.first && l.second == r.second);
}
Run Code Online (Sandbox Code Playgroud)
但是你真的不需要自己实现它,除非你想以不同的方式实现它。该标准库已经提供了一个通用版本的operator==
用于std::pair
其在一对值按字母顺序比较,像我上面那样,即比较first
与first
和second
使用second
。如果您需要对它们进行不同的比较,则只有提供您自己的特定定义(非模板版本)。
上面提到的几点值得注意,关于如何operator==
在定义的类型需要时实现。