2011-09-22 65 views
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的内容目的。那怎么样?

回答

2

该常量是关于该类的成员。您无法更改v._vec的值,但更改v._vec指向的内存的内容没有任何问题。

+1

因此,const运算符[]返回一个const int&?会更好吗? – azphare

+2

@azphare是,'v [1] = 15;'然后是编译器错误。顺便说一句,不要忘记'delete [] _vec'的析构函数。 – jrok