更改 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 对象的内容。怎么样才算好呢?
Can anyone explain to me why the following code works:
#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;
}
It compiles and runs just fine, even though we're changing the contents of a const object. How is that okay?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
常量是针对类成员的。您无法更改
v._vec
的值,但更改v._vec
指向的内存内容没有问题。The constness is with regards to the members of the class. You cannot change the value of
v._vec
, but there's no problem changing the content of the memory thatv._vec
points to.