重载<运算符在另一个类中使用时"no matching function for call"错误
overloaded < operator gives "no matching function for call" error when used in another class
我实现了一个自定义TimeStruct类,其中我声明<操作员如下
bool operator<(const TimeStruct t2) const;
实现如下。
bool TimeStruct::operator<(const TimeStruct t2) const
{
//do something, I don't include the actual implementation
return true;
}
然后我有另一个类X,这个TimeStruct类是一个成员,让我们调用这个成员字段Y。我正在使用一个向量,我想在类X的Y字段上对这个向量进行排序。因此,我需要指定一个方法,该方法可能作为向量排序方法的基础。
因此,我在X中声明了一个额外的方法来比较不同的X。
bool compareX(const X& x1, const X& x2) const;
实现如下:
bool X::compareX(const X& x1, const X& x2) const
{
return (x1.Y.operator<(x2.Y));
}
不幸的是,此代码无法编译。我收到以下错误。
No matching function call for TimeStruct::operator<(const TimeStruct&) const
candidates are : bool TimeStruct::operator<(TimeStruct&) const
最近一个小时我一直在抓头发,有人能指出我做错了什么吗。
您需要通过TimeStruct
运算符中的常量引用:
bool operator<(const TimeStruct& t2) const;
并且,根据错误消息,您已经提供了
bool operator<(TimeStruct&) const
运算符声明中需要一个const引用说明符。
此外,您可能希望将operator<
从成员函数转换为好友函数。这通常是最好的做法。
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- "no matching function for call to 'Vector::Vector'"错误
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 从 TVector2 类派生复杂类:"No matching function for call to Complex::Complex()"
- 学习 c++,编译错误"no matching function for call"
- C++ "error: no matching function"
- 尝试实例化模板类的对象时出现"No Matching Constructor"错误
- 结构错误:"no matching function for call to "
- 创建函数变体向量时"No matching function for call"错误
- 为什么"std::isdigit"在 Windows 上报告C++"no matching overloaded function"
- 编译时二叉搜索树错误的反向迭代器表示"no matching function call for operator=()"
- 如果子类中没有构造函数方法,则错误"no matching function for call to 'LGame::LGame(String&)'"
- 提升多精度浮点数128:标准::exp错误:'no matching function for call'
- "error: no matching function for call to",我无法更改结构的定义
- 替换派生对象向量中的对象"no matching function to call"
- 我的程序显示许多错误,"error: no matching function for call to 'getPercentScore'"
- 为什么即使我定义了它们"no matching overload found"也会出现错误
- 为什么有一个指向此代码行(第 7 行)的"no matching call for function"错误?