开发者

Changing the elements of an array member of a const object

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?


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 that v._vec points to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜