const成员函数重载-error C2678 二进制< 没有找到接受const类型的左操作数的运算符

原文地址这里写链接内容
最近遇到的一个错误,重载类的小于比较操作符,然后通过algorithm中的sort对其进行排序时提示了一个编译错误:
1>—— 已启动生成: 项目: T, 配置: Debug Win32 ——
1>正在编译…
1>Main.cpp
1>e:\code\X\t\t\main.cpp(34) : warning C4996: ‘freopen’: This function or variable may be unsafe. Consider using freopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files\microsoft visual studio 9.0\vc\include\stdio.h(252) : 参见“freopen”的声明
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(143) : error C2678: 二进制“<”: 没有找到接受“const Node”类型的左操作数的运算符(或没有可接受的转换) 1> e:\code\X\t\t\main.cpp(18): 可能是“bool Node::operator <(const Node &)” 1> 试图匹配参数列表“(const Node, const Node)”时
1> c:\program files\microsoft visual studio 9.0\vc\include\functional(142): 编译类 模板 成员函数“bool std::less<_Ty>::operator ()(const _Ty &,const _Ty &) const”时
1> with
1> [
1> _Ty=Node
1> ]
1> c:\program files\microsoft visual studio 9.0\vc\include\queue(223): 参见对正在编译的类 模板 实例化“std::less<_Ty>”的引用
1> with
1> [
1> _Ty=Node
1> ]
1> e:\code\X\t\t\main.cpp(53): 参见对正在编译的类 模板 实例化“std::priority_queue<_Ty>”的引用
1> with
1> [
1> _Ty=Node
1> ]
1>生成日志保存在“file://e:\Code\X\T\T\Debug\BuildLog.htm”
1>T – 1 个错误,1 个警告
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

原因就是因为重载<操作符的时候,没有把函数定义为const成员函数,而从错误提示信息中看得到默认的less算子传入的两个参数都是const引用形式的,他们会尝试调用const版本的比较操作(有没有const会构成重载)。下面是一个样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

include

using namespace std;

class Test
{
public:
Test(int val):value(val)
{
}
private:
int value;
public:
bool operator<(const Test& rhs)
{
cout << “none-const member function called…” << endl;
return value < rhs.value;
}
bool operator<(const Test& rhs) const
{
cout << “const member function called…” << endl;
return value < rhs.value;
}
};

bool TestFun(const Test& lhs, const Test& rhs)
{
return lhs < rhs;
}

bool TestFun2(const Test& lhs, Test& rhs)
{
return lhs < rhs;
}

bool TestFun3(Test& lhs, const Test& rhs)
{
return lhs < rhs;
}

bool TestFun4(Test& lhs, Test& rhs)
{
return lhs < rhs;
}

int main(int argc, char **argv)
{
Test a(10), b(100);
TestFun(a, b);
TestFun2(a, b);
TestFun3(a, b);
TestFun4(a, b);

return 0;

}
输出结果为:
error C2678:二进制<:没有找到接受const类型的左操作数的运算符

猜你喜欢

转载自blog.csdn.net/u013992365/article/details/69664989
今日推荐