【问题标题】:Difference between const and non-const method?const和非常量方法的区别?
【发布时间】:2015-05-28 19:24:41
【问题描述】:
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)

【问题讨论】:

  • 你试过使用 const_iterator 吗?

标签: c++ vector type-conversion constants


【解决方案1】:

要解决您的问题,您必须使用 const_iterator

原因如下:该方法被标记为 const,这意味着该方法本身不会改变调用该方法的对象实例的状态。

因此,在 const 方法中,您不能在同一对象上调用未标记为 const 的任何其他方法。当然,因为新调用并不能保证它是 const,所以第一个方法不能再声称是 const。

通过声明迭代器 const,您将使用 lower_bound 的 const 版本。

【讨论】:

    【解决方案2】:

    尝试使用const_iterator

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

    【讨论】:

    • 这正是您通常使用auto 处理此类事情的原因。
    【解决方案3】:

    考虑使用 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,编译器会推断出正确的迭代器类型,而无需您在代码中明确地“拼写”它。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-23
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      相关资源
      最近更新 更多