更改const对象的数组成员的元素

Changing the elements of an array member of a const object

本文关键字:组成员 元素 数组 更改 对象 const      更新时间:2023-10-16

谁能给我解释一下为什么下面的代码工作:

#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指向的内存的内容是没有问题的。