art*_*oon 1 c++ overloading operator-keyword
I tried to overload the operator !=
struct Antichoc
{
quint8 Chariot;
quint8 Frittage;
bool operator!=(const Antichoc &a, const Antichoc &b)
{
return a.Chariot != b.Chariot || a.Frittage != b.Frittage;
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
bool Antichoc :: operator!=(const Antichoc&,const Antichoc&)必须只有一个参数
为什么这个错误
非静态成员函数采用隐式的隐藏第一个参数,其中指针指向同一类型.所以你的成员运营商实际上有三个参数,它应该有两个参数.
您可以将其设为非成员运营商:
struct Antichoc { .... };
bool operator!=(const Antichoc &a, const Antichoc &b)
{
return a.Chariot != b.Chariot || a.Frittage != b.Frittage;
}
Run Code Online (Sandbox Code Playgroud)
或者让它成为只有一个参数的成员.
struct Antichoc
{
quint8 Chariot;
quint8 Frittage;
bool operator!=(const Antichoc& rhs) const
{
return Chariot != rhs.Chariot || Frittage != rhs.Frittage;
}
};
Run Code Online (Sandbox Code Playgroud)
第一个版本允许隐式转换Antichoc,这在此特定示例中不是必需的.
通常,这是一种很好的实践!=方式==.
请注意,在C++ 11中,您可以使用以下方法简化所有这些逻辑运算符std::tie:
#include <tuple>
bool operator!=(const Antichoc &a, const Antichoc &b)
{
return std::tie(a.Chariot, a.Frittage) != std::tie(b.Chariot, b.Frittage);
}
Run Code Online (Sandbox Code Playgroud)