考虑以下代码:
#include <vector>
using namespace std;
struct foo
{
void bar()
{
}
};
int main()
{
{
vector<foo*> a;
a.push_back(new foo());
a.push_back(new foo());
a.push_back(new foo());
vector<foo*>::const_iterator itr = a.begin();
(*itr)->bar(); // compiles - this becomes more confusing
// when found in a const method. On first
// glance, one will (or at least me) may
// assume that bar() must be const if the
// method where it is being called from is
// const
// The above compiles because internally, this is what happens
// (ignore the fact that the pointer has not been newd)
foo* const * element;
(*element)->bar(); // compiles
// What I would expect however (maybe it is just me) is for const_iterator
// to behave something like this
const foo* const_element;
const_element->bar(); // compile error
}
{
vector<foo> a;
a.resize(10);
vector<foo>::const_iterator itr = a.begin();
itr->bar(); // compile error
}
}
我明白为什么可以调用它。像这样const_iterator
存储 const-ness:const T*
指针转换foo* const *
为对象并转换为对象foo const *
。
所以我的问题是,为什么我们可以从 a 调用非常量成员函数const_iterator
?不允许从 a 调用非常量成员函数不是更直观const_iterator
吗?带有 const 选项的 s 设计不应该iterator
阻止这种行为吗?
现在更重要的问题是:如果我想const_iterator
禁止调用指向对象的非常量成员函数怎么办?