-
Question
Hi
I'm writing a very simple program. Im supposed to create an object that contains an array in it.
For instance:
calss intArr
{
public:
intArr(int size);
int operator [] (int index);
int * Arr;
private:
int size
}
the point of this small exercise is to be able to do the following:
void main()
intArr mainArr(10);
mainArr[3]=7;
the idea is to be able to refer to a specific element just like any other built in type array, instead of having to write: mainArr.Arr[3]=7
However, whenever I perform this assignment I get a compilation error:
left operand must be l-value.
When I write the following : i=mainArr[3] there is no problem.
Here's my operator [] implementation :
int intArr operator [] (int index)
{
return Arr[index]
}
what am I doing wrong here?
thanks
Gozlan
-
Lots of typos for a start..
Also, operator[] was not shown to be a member of intArr in your code.....also if you want to assign to the array like that, then you need to return a reference....not a normal int. Also, you dont show to be managing memory.....
Here's a rather rushed example;
Code:
class intArr
{
public:
intArr(int size);
~intArr(){delete[] Arr;}
int& operator [] (int index);
private:
int size;
int * Arr;
};
intArr::intArr(int sz){
Arr = new int[sz];
if(!Arr){/*Error management here*/}
}
int& intArr::operator [] (int index)
{
return Arr[index];
}
int main(){
intArr mainArr(10);
mainArr[3] = 7;
std::cout << mainArr[3];
}
-
Thanks Fordy!
It did the trick...
cheers
gozlan