Reputation: 201
I'm trying to make my own string class in c++11 but I have some problems. comparing my class to the std::string class, I can't figute out how to use the
std::string.at(int) = 'a'; method/overloading.
I've created the at(int) method in my own class:
int at(int index)
{
if(index <0 || index > size-1) {throw std::out_of_range("Error, index out of range");}
return data[index];
}
and it workd well if I only use:
MyString.at(2);
In the main file:
MyString = "Hello world!"; //Works fine!
MyString.at(2)='a'; //Gives, Error: expressino must be a modifiable Ivalue.
Any help with this would be great, Thanks!
Upvotes: 4
Views: 479
Reputation:
At least one of your at()
member functions needs to return a non-const reference to char
. Like this:
char &at(std::size_t idx)
{
return data[idx];
}
It would be beneficial to define a const
version of the function too:
const char &at(std::size_t idx) const
{
return data[idx];
}
Also note the use of std::size_t
(which is an unsigned type guaranteed to be large enough to represent any size). This way you improve portability and you don't have to check for negative indices.
Upvotes: 3
Reputation: 56863
You are returning an integer and not a reference to the character, you probably want:
char& at(int index)
Of course, you need to return the correct character type, but in any case you need to return a reference in order for the caller to be able to assign to it.
Upvotes: 1