错误:传递"常量..."作为"这个"的论点"..."丢弃限定符
error: passing ‘const ...'’ as ‘this’ argument of ‘...’ discards qualifiers
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 个双精度和一个 int 的文件。我们通过字符串符号和索引增益对程序进行排序。这本书指导我使用向量来存储每个数据。如下所示,重载运算符比较每个符号,并使用容器的排序成员函数对其进行排序。我的问题是为什么我必须在过载操作员前面放置一个常数以进行>和<。但不适用于>=、<=、==、!= 重载运算符。
//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());
}
错误消息告诉您,您正在operator<
函数中从对象强制转换const
。应向不修改成员的所有成员函数添加const
。
bool operator<(const stockType& stock) const
// ^^^^^
{
return (symbols < stock.symbols)
}
编译器抱怨operator<
的原因是因为std::sort
使用operator<
来比较元素。
此外,您在insert
函数中还有另一个语法错误。
更新:
void insert(const& stockType item);
自:
void insert(const stockType& item);
// ^^
相关文章:
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 如何在函数中传递常量变量?
- 为什么我们需要传递常量共享指针作为引用?
- 如何在C++中通过命令行参数传递常量 int
- 英特尔 TBB,parallel_pipeline,当我在阶段之间传递常量字符*时出错
- 为什么要在具有多个参数的重载运算符+中传递常量引用
- 传递常量指针
- 在 Argv 主参数中传递常量字符
- 传递常量引用与创建临时常量副本相同,那么为什么要传递常量引用
- 错误:传递"常量..."作为"这个"的论点"..."丢弃限定符
- 在C++中,通过引用传递常量布尔值是不是不好的
- 如何传递常量对象
- 为什么不总是在C++中传递常量引用
- 从对象成员传递常量引用.IE someObject.function()
- 如何在参数非常量中传递常量指针
- 错误:传递"常量..."作为"这个"的论点"..."丢弃限定符
- C++:传递常量引用的常量指针时出错
- 传递常量副本
- 正在传递常量指针..我需要做吗
- 传递常量将通过引用自动传递