const 和非常量方法之间的区别?
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;
}
您好,当我尝试编译它时,它在第三行抛出错误:
"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
当我将函数 CountCars 设置为非常量时,它编译没有问题。我应该改变什么来解决这个问题? (函数必须是常量)
尝试使用 const_iterator
:
vector<CDriver>::const_iterator Diterator
// ^^^^^^
要解决您的问题,您必须使用 const_iterator
原因如下:该方法被标记为 const,这意味着该方法本身不会更改调用该方法的对象实例的状态。
因此,在 const 方法中,您不能在未标记为 const 的同一对象上调用任何其他方法。因为当然 new 调用不能保证它是 const 所以第一个方法不能再声称是 const 了。
通过声明迭代器 const,您将使用 lower_bound 的 const 版本。
考虑使用 const_iterator
,例如
vector<CDriver>::const_iterator Diterator
= lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);
如果您可以在 C++11/14 中编译,使用 auto
也有帮助:
auto Diterator = lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);
(使用 auto
,编译器会推导出正确的迭代器类型,而不需要您在代码中明确地 "spell" 它。)
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;
}
您好,当我尝试编译它时,它在第三行抛出错误:
"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
当我将函数 CountCars 设置为非常量时,它编译没有问题。我应该改变什么来解决这个问题? (函数必须是常量)
尝试使用 const_iterator
:
vector<CDriver>::const_iterator Diterator
// ^^^^^^
要解决您的问题,您必须使用 const_iterator
原因如下:该方法被标记为 const,这意味着该方法本身不会更改调用该方法的对象实例的状态。
因此,在 const 方法中,您不能在未标记为 const 的同一对象上调用任何其他方法。因为当然 new 调用不能保证它是 const 所以第一个方法不能再声称是 const 了。
通过声明迭代器 const,您将使用 lower_bound 的 const 版本。
考虑使用 const_iterator
,例如
vector<CDriver>::const_iterator Diterator
= lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);
如果您可以在 C++11/14 中编译,使用 auto
也有帮助:
auto Diterator = lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);
(使用 auto
,编译器会推导出正确的迭代器类型,而不需要您在代码中明确地 "spell" 它。)