I know that in C++ functions can be overloaded by their const property, but I got an error when I run this piece of code:
#include <iostream>
#include <conio.h>
using namespace std;
template<class T> class Array
{
public:
Array() : data(0), sz(0){}
Array(unsigned size) : sz(size), data(new T[size]){}
~Array()
{
delete[] data;
}
const T& operator[](unsigned n) const
{
if(n >= sz || data == 0)
{
throw "Array subscript out of range";
}
return data[n];
}
T& operator[](unsigned n)
{
if(n >= sz || data == 0)
{
throw "Array subscript out of range";
}
return data[n];
}
operator const T*() const
{
return data;
}
operator T*()
{
return data;
}
private:
T* data;
unsigned sz;
Array(const Array& a);
Array& operator=(const Array&);
};
int main()
{
Array<int> IntArray(20);
for(int i = 0; i != 20; ++i)
{
IntArray[i] = i;
}
return 0;
}
The error comes from IntArray[i] = i;
the complier says that it can't find the proper overload function.
shouldn't it call T& operator[](unsigned n)
??
I'm using vs2010 as my complier
Thanks for any help.