简体   繁体   中英

C++ Operator overloading, my own string class

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM