2013-09-29 70 views
13

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

'常量与stockType item'应该是:'常量stockType&item' – billz

+0

OK非常感谢球员我很感激 – Emy

回答

20

错误消息告诉你,你,你是从你的对象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); 
//       ^^ 
相关问题