0
Help with creating arrays?
https://code.sololearn.com/cC6LlNe7zCvi/?ref=app In my class Array, I want to overload the []-operator so that I can not only get a value, but also use it to assign a value to the array. My idea was that I need a function to return a pointer to the array/to the position in the array I want to assign the value to. Am I right on this and just failed to execute it? Or is my assumption completely wrong and I need a different view on the problem? A detailed explanation is deeply appreciated!
2 Answers
+ 2
I assume you want to do something like
arr[0] = 5;
arr[1] = 3;
etc...
The operator[] should return a reference, not a copy.
A& operator[](int pos) {
return myArray[pos];
}
The reason for this is that if you don't use a reference and return a copy instead you return an rvalue, rvalues cannot be assigned anything.
For example if you return 5 and want to assign 3 to it you are basically saying
5 = 3, which makes no sense.
If you return a reference you return an lvalue, which can be modified.
Some_address_in_memory = 3, this of course does make sense.
Lastly there should also be a const version for the operator[]
const A& operator[](int pos) const {
return myArray[pos];
}
Random tips:
You should use std::size_t for indexes, not an int, because an int can represent negatives and negative indexes for an array make no sense either ^^.
Don't forget delete in the destructor, since you used a new.
Inside the string function:
void operator=(std::string s) {
this->str = s;
}
should return a reference to itself, this is to allow chaining. ( return *this; )
e.g. a = b = c = d;
Also you probably want to take std::string as a const reference too.
0
Thank you so much for helping me out with this code again!
Now that you explained things they seem so obvious to me...
Im always mad if I cant solve things on my own, but I guess sometimes asking others is really the only way^^.