【问题标题】:Qt operator != overloadingQt 运算符 != 重载
【发布时间】:2013-06-10 09:28:08
【问题描述】:
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;
}
}
我得到错误:
bool Antichoc::operator!=(const Antichoc&, const Antichoc&) 必须取
正是一个论点
为什么会出现这个错误
【问题讨论】:
标签:
c++
overloading
operator-keyword
【解决方案1】:
非静态成员函数采用隐式隐藏的第一个参数和指向同一类型的指针。所以你的成员操作符实际上有三个参数,它应该有两个。
您可以将其设为非成员运算符:
struct Antichoc { .... };
bool operator!=(const Antichoc &a, const Antichoc &b)
{
return a.Chariot != b.Chariot || a.Frittage != b.Frittage;
}
或者让它成为一个只接受一个参数的成员。
struct Antichoc
{
quint8 Chariot;
quint8 Frittage;
bool operator!=(const Antichoc& rhs) const
{
return Chariot != rhs.Chariot || Frittage != rhs.Frittage;
}
};
第一个版本允许隐式转换为 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);
}