2010-10-02 87 views
0

我有這段代碼試圖保護用戶不受數組邊界錯誤的影響。const array改變問題C++

我不明白爲什麼這會編譯,我宣佈數組爲const,因此,我想要得到一個編譯錯誤!

非常感謝。

/************ file: SafeAccessArray.h ********************/ 
template<typename T> 
class SafeAccessArray 
{ 
private: 
int _len; 
T * _arr; 
public: 
SafeAccessArray (int len=2) : _len (len), _arr (new T [len]) {} 
~SafeAccessArray() { delete _arr; } 
T& operator [](int i) const 
{if (i < 0 || i >= _len) throw (-1); 
else return _arr[i]; } 
}; 
/************ end of file: SafeAccessArray.h *************/ 

/************ file: SafeAccessArray1.cpp *************/ 
#include "SafeAccessArray.h" 
int main()`enter code here` 
{ 
SafeAccessArray<int> intArr (2); 
intArr[0] = 0; 
intArr[1] = 1; 
const SafeAccessArray<int> intArrConst (2); // THIS IS THE "PROBLEMATIC" LINE 
intArrConst [0] = 0; 
intArrConst [1] = 1; 
return 0; 
} 
/************ end of file: SafeAccessArray1.cpp ******/ 
+3

'SafeAccessArray'需要一個拷貝構造函數和賦值操作符。查看[Rule of Three](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29)以及copy-and-swap idiom。即使這是個好主意,只要私下使用'std :: vector'就可以完成它了。另外,不要拋出整數,拋出來自'std :: exception'的東西; 'std :: out_of_range'等待。 – GManNickG 2010-10-02 19:14:32

+2

請不要拋出'-1',即使在測試代碼中也不要。拋出':: std :: out_of_range'或者什麼,除了像'int'或'char *'這樣的基本類型,最好是從':: std :: exception'派生的東西。 – Omnifarious 2010-10-02 19:21:46

+2

另外,new []帶有delete [],而不是刪除。 – sellibitze 2010-10-02 19:21:52

回答

4

是啊,這是const,但你沒有T& operator [](int i) const反正。你正在返回一個引用,並且這個函數可以在一個const對象上被調用。

讓它返回const T&。更好的是,停下來。只需使用std::vectorat()函數。

+0

所以,只是爲了說清楚,當我調用「intArrConst [0] = 0」 - 運算符[]會導致強制轉換爲非const對象,否則該賦值不會真的發生在我的const對象上? – limlim 2010-10-02 19:27:00

+0

@limlim:什麼?當你說'intArrConst [0]'時,調用T&operator [](int i)const'。這會導致一個'T&',然後給它賦0,改變引用(這是一個別名,只是改變了它的別名值。) – GManNickG 2010-10-02 19:31:43

+1

@limlim:類包含'T * _arr;''const這個類的實例包含一個'T * const _arr',而你希望它有'T const * const _arr'。 C++沒有增加你想要的額外資格,所以擔保是你的責任。 – Potatoswatter 2010-10-02 19:38:59

2

我認爲operator[]成員函數希望以下兩種重載變體:

T& operator [](int i); 
const T& operator [](int i) const; 

該一個提供

T& operator [](int i) const; 

不匹配任何上述的,因此該問題。