十年前写的一个C++项目编译报错:“bool compatetor_asc::operator ()(const std::wstring &,const std::wstring &)”: 不能将“this”指针从“const compatetor_asc”转换为“compatetor_asc &”。
对应的代码如下 :
class compatetor_asc
{
public:
bool operator()(const std::wstring& lhs, const std::wstring& rhs)
{
return lhs < rhs ;
}
};
这段代码重载了函数调用操作符()
,可以让该类的对象能够像函数一样使用。调用的代码std::set<std::wstring, compatetor_asc> m_OriginalAsc;
。
当时这个C++项目是用VS2008开发的,C++标准是C++03,现在用VS2022来编译,用的C++标准是C++14。
简单解了一下,原来从C++11开始,标准库排序谓词函数就要求必须是const成员函数了,那么只要把operator()
函数改为const成员函数即可。
bool operator()(const std::wstring& lhs, const std::wstring& rhs) const
{
return lhs < rhs ;
}
修改后再次编译,问题解决。
后记:
已经有近十年没有写过C++项目了,最初学习C++用的是VC++6.0,标准是C++98,到后来有了C++03,现如今已经到了C++23了,二十年如一梦。