2
谁能向我解释的元素,为什么下面的代码工作:改变const对象的数组成员
#include <iostream>
class Vec
{
int *_vec;
unsigned int _size;
public:
Vec (unsigned int size) : _vec (new int [size]), _size(size) {};
int & operator[] (const int & i)
{
return _vec[i];
}
int & operator[] (const int & i) const
{
return _vec[i];
}
};
int main()
{
const Vec v (3);
v[1] = 15;
std::cout << v[1] << std::endl;
}
它编译和运行得很好,即使我们改变一个const的内容目的。那怎么样?
因此,const运算符[]返回一个const int&?会更好吗? – azphare
@azphare是,'v [1] = 15;'然后是编译器错误。顺便说一句,不要忘记'delete [] _vec'的析构函数。 – jrok