c++ - `bool operator<(Contact&)' 必须正好有两个参数

标签 c++ comparison operator-overloading overloading operator-keyword

我有

class Conatact{
.....
bool operator<(Contact &c);
};

bool operator<(Contact &c)
{
     return this.getName<c.getName();

}

它说“bool operator<(Contact&)”必须恰好接受两个参数 当我尝试将其更改为有两个参数时

bool operator<(Contact &c)
{
     return this.getName<c.getName();

}

它说它必须恰好接受一个参数

最佳答案

我认为您需要通过提供完全限定名称向编译器表明它是一个成员实现:

bool Conatact::operator<(Contact &c)
{
     return this->getName() < c.getName();
}

最好让你的操作符const,同时让Contact &c const

如果没有范围解析限定符,编译器会认为您正在定义一个“独立”运算符来比较联系人,在这种情况下,该运算符确实需要采用两个参数:

bool operator<(const Contact &lhs, const Contact &rhs) {
    ...
}

关于c++ - `bool operator<(Contact&)' 必须正好有两个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107736/

相关文章:

c++ - 未定义的模板成员引用

c++ - 在调度表中的类外使用模板类方法

c# - 为什么这个 DirectoryInfo 比较不起作用?

c++ - 在 C++ 中重载 << 运算符?

c++ - 理解 operator() 重载

c++ - 如何创建一个继承自QWidget的qt插件

C++ 重载与有符号和无符号 int 不同

r - same(x, y) 和 isTRUE(all.equal(x, y)) 有什么区别?

javascript - 在 JavaScript 中,typeof x == 'y' 和 typeof x === 'y' 之间有什么区别吗?

c++ - 如何在 C++ 中使用运算符重载来显示类(游戏板)