2011-09-22 188 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