首页 > 解决方案 > 什么时候可以用 const 装饰调用我的重载函数?

问题描述

在下面的代码中,我有两个begin()功能。什么时候调用第二个 ( const) 版本?我问的原因是因为STL向量具有相似的特征,但可以正确调用。我希望该行将 abc.begin(); 调用const该函数的版本begin,但事实并非如此。

#include <vector>
using namespace std;

class test {
 public:
  test(vector<int> const &x) : a{x} {};
  test(vector<int> &x) : b{x} {};
  vector<int> begin() {
    cout << "int begin() is called" << endl;
    return b;
  }
  const vector<int> begin() const {
    cout << "int const begin() const is called" << endl;
    return a;
  }
 private:
  const vector<int> a;
  vector<int> b;
};

int main() {
  vector<int> b{1, 2, 3, 4, 5};
  const vector<int> a{4, 5, 6, 7, 8};
  test abc{a};
  test bcd{b};
  bcd.begin();
  abc.begin();
  return 0;
}

来自 STL 向量的代码示例

    iterator begin() _NOEXCEPT
        {return __make_iter(0);}
    const_iterator begin() const _NOEXCEPT
        {return __make_iter(0);}

标签: c++c++17

解决方案


现在我想通了。为了使用 const 成员函数,我们需要将实例声明为常量,即

常量测试 abc{a};


推荐阅读