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的內容目的。那怎麼樣?
因此,const運算符[]返回一個const int&?會更好嗎? – azphare
@azphare是,'v [1] = 15;'然後是編譯器錯誤。順便說一句,不要忘記'delete [] _vec'的析構函數。 – jrok