简体   繁体   English

C ++运算符重载,我自己的字符串类

[英]C++ Operator overloading, my own string class

I'm trying to make my own string class in c++11 but I have some problems. 我试图在c ++ 11中创建自己的字符串类,但是我遇到了一些问题。 comparing my class to the std::string class, I can't figute out how to use the 比较我的类和std :: string类,我无法弄清楚如何使用

std::string.at(int) = 'a'; std :: string.at(int)='a'; method/overloading. 方法/过载。

I've created the at(int) method in my own class: 我在自己的类中创建了at(int)方法:

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 . 至少有一个at()成员函数需要返回对char的非const引用。 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版本也是有益的:

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). 还要注意使用std::size_t (这是一个无符号类型,保证足够大以表示任何大小)。 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. 当然,您需要返回正确的字符类型,但无论如何您需要返回一个引用,以便调用者能够分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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