从常量成员函数返回迭代器

0x6*_*773 0 c++ g++ c++11 c++14

在下面的代码中,为什么返回类型foo::func是,vector<int>::const_iterator而不是vector<int>::iterator我返回的对象vector<int>::iterator.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class foo
{
private:
  vector<int> ar;
public:
  foo()
  {
    ar.resize(10);
    iota(ar.begin(), ar.end(), 1);
  }
  auto func() const
  {
    return ar.begin() + 5;
  }
};

int main()
{
  foo x;
  cout<<boolalpha<<endl;
  auto it = x.func();
  cout<<is_same<decltype(it), vector<int>::iterator>::value<<endl;
  cout<<is_same<decltype(it), vector<int>::const_iterator>::value<<endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

上述代码的输出是:

false
true
Run Code Online (Sandbox Code Playgroud)

相反,如果我重新定义foo::func()

auto func()
{
    return ar.begin() + 5;
}
Run Code Online (Sandbox Code Playgroud)

输出将是

true
false
Run Code Online (Sandbox Code Playgroud)

为什么常量成员函数将返回类型更改为常量?我是否需要删除const关键字以使返回类型为vector<int>::iterator或有其他方式吗?

Bar*_*rry 5

声明的成员函数const会影响this指针的类型.内func(),this有类型const foo*.因此,通过const this指针访问的所有成员类型本身都是const,因此隐式类型ar实际上是const std::vector<int>.在两个begin()重载中vector,唯一可行的重载是const重载,它返回一个const_iterator.

当您重新定义func()为非const,则类型this是简单的foo*,因此成员的类型ar是,std::vector<int>并且begin()返回的重载iterator是首选.