2013-09-29 42 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); 
//       ^^ 
相關問題