错误:传递'const ...''作为'''的'this'参数会丢弃限定符

时间:2013-09-29 03:08:51

标签: c++

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的文件。我们通过字符串符号和索引增益来整理程序。这本书指示我使用向量来存储每个数据。如下所示,重载运算符会比较每个符号,并使用容器的排序成员函数对其进行排序。我的问题是为什么我必须在&gt;的重载运算符前面加一个常量?和&lt;。但不适用于&gt; =,&lt; =,==,!=重载运算符。

//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());
     }

1 个答案:

答案 0 :(得分:20)

错误消息告诉您,您正在const函数中的对象中投射operator<。您应该将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);
//                         ^^
相关问题