stockListType.cpp:58: instantiated from here
/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
Above is the error I got and would like someone to explain to me what it means. I solved the error by placing a constant in front of the overloading operator. My program was a stock market application that read a file that includes a string, 5 doubles and an int. We sort out the program by the string symbols and the index gain. The book instructed me to use vectors to store each data. As you see below the overload operator compares each symbol and sorts it out using the sort member function of containers. My question is why did I have to put a constant in front of the overload operator for > and <. but not for >=, <=, ==, != overload operators.
//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());
}
The error message tells you that you that you are casting of const
from your object in operator<
function. You should add const
to all member functions that don't modify member.
bool operator<(const stockType& stock) const
// ^^^^^
{
return (symbols < stock.symbols)
}
The reason why compiler complains about operator<
is because std::sort
uses operator<
to compare the elements.
Also you have another syntax error in insert
function.
Update:
void insert(const& stockType item);
to:
void insert(const stockType& item);
// ^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With