[英]Problem with const *this portion of a C++ 2D Array templated class
[英]Problem with const array changing 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 ******/
是的,它是const
,但無論如何,您都做了T& operator [](int i) const
。 您將返回一個引用,並且可以在const對象上調用此函數。
使它返回const T&
。 更好的是,停止。 只需使用std::vector
和at()
函數即可。
我認為operator[]
成員函數需要以下兩個重載的變體:
T& operator [](int i);
const T& operator [](int i) const;
提供一個
T& operator [](int i) const;
與以上任何一項都不匹配,因此是問題所在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.