任何人都可以向我解释为什么以下代码有效:
#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 对象的内容,它也能正常编译和运行。怎么样?
最佳答案
常量是关于类的成员的。您无法更改 v._vec
的值,但是更改 v._vec
指向的内存内容没有问题。
关于c++ - 更改 const 对象的数组成员的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7512569/