简体   繁体   中英

Difference between const and non-const method?

int CRegister::CountCars(const string& name, const string& surname)const{
const pair<string,string> wholename(name,surname);
vector<CDriver>::iterator Diterator=lower_bound(m_Drivers.begin(),m_Drivers.end(),wholename);
if (Diterator<m_Drivers.end()){
    if(Diterator->m_name.compare(wholename.first)!=0 || Diterator->m_surname.compare(wholename.second)!=0) return 0;
    return Diterator->m_DriversNumber;
}
return 0;
}

Hello, when I try to compile this, it throws error on the third line:

"conversion from ‘__gnu_cxx::__normal_iterator<const CDriver*, std::vector<CDriver> >’ to non-scalar type ‘std::vector<CDriver>::iterator {aka __gnu_cxx::__normal_iterator<CDriver*, std::vector<CDriver> >}’ requested

When I set the function CountCars as a non-const, it compiles without problems. What should I change to fix this? (the function has to be const)

To solve your problem you have to use a const_iterator

The reason is the following : The method is marked const, which means that the method itself is not going to change state of the object instance upon which the method is invoked.

Therefore within a const method you cannot call any other method on the same object that is not marked const. Because of course that new call does not garantee that it is const so can the first method not claim to be const anymore.

by declaring the iterator const you are going to use the const version of lower_bound.

Try using a const_iterator :

vector<CDriver>::const_iterator Diterator
//               ^^^^^^

Consider using a const_iterator , eg

vector<CDriver>::const_iterator Diterator 
    = lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);

If you can compile in C++11/14, using auto helps as well:

auto Diterator = lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);

(With auto , the compiler deduces the correct iterator type, without requiring you to correctly "spell" it explicitly in code.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM