stockListType.cpp:58:从这里实例化
/usr/include/c++/4.2.1/bits/stl_algo.h:91: error: passing ‘const stockType’ as ‘this’ argument of ‘bool stockType::operator<(const stockType&)’ discards qualifiers
/usr/include/c++/4.2.1/bits/stl_algo.h:92: error: passing ‘const stockType’ as ‘this’ argument of ‘bool stockType::operator<(const stockType&)’ discards qualifiers
/usr/include/c++/4.2.1/bits/stl_algo.h:94: error: passing ‘const stockType’ as ‘this’ argument of ‘bool stockType::operator<(const stockType&)’ discards qualifiers
/usr/include/c++/4.2.1/bits/stl_algo.h:98: error: passing ‘const stockType’ as ‘this’ argument of ‘bool stockType::operator<(const stockType&)’ discards qualifiers
/usr/include/c++/4.2.1/bits/stl_algo.h:100: error: passing ‘const stockType’ as ‘this’ argument of ‘bool stockType::operator<(const stockType&)’ discards qualifiers
上面是我得到的错误,希望有人向我解释它的含义。我通过在重载运算符前面放置一个常量解决了该错误。我的程序是一个股票市场应用程序,它读取一个包含一个字符串、5 个双精度数和一个整数的文件。我们通过字符串符号和索引增益对程序进行排序。书上指导我使用向量来存储每个数据。如下所示,重载运算符比较每个符号并使用容器的排序成员函数对其进行排序。我的问题是为什么我必须在 > 和 =、
//function was declared in stockType.h and implemented in stockType.cpp
bool operator<(const stockType& stock)//symbol is a string
{
return (symbols < stock.symbols)
}
//The function below was defined in stockListType.h and implemented in
// stockListType.cpp where I instantiated the object of stockType as a vector.
//vector<stockType> list; was defined in stockListType.h file
void insert(const& stockType item)
{
list.push_back(item);
}
void stockListType::sortStockSymbols()
{
sort(list.begin(), list.end());
}
错误消息告诉您您正在转换const
从你的对象operator<
功能。你应该添加const
到所有不修改成员的成员函数。
bool operator<(const stockType& stock) const
// ^^^^^
{
return (symbols < stock.symbols)
}
编译器抱怨的原因operator<
是因为std::sort http://en.cppreference.com/w/cpp/container/list/sort uses operator<
来比较元素。
另外你还有另一个语法错误insert
功能。
Update:
void insert(const& stockType item);
to:
void insert(const stockType& item);
// ^^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)