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

标签 c++ string c++11 operator-overloading

我正在尝试在 C++11 中创建我自己的字符串类,但我遇到了一些问题。 将我的类与 std::string 类进行比较,我不知道如何使用

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

我在自己的类中创建了 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];
}

如果我只使用它,效果很好:

MyString.at(2);

在主文件中:

MyString = "Hello world!"; //Works fine!
MyString.at(2)='a'; //Gives, Error: expressino must be a modifiable Ivalue.

任何帮助都将非常有用,谢谢!

最佳答案

至少您的 at() 成员函数之一需要返回对 char 的非常量引用。像这样:

char &at(std::size_t idx)
{
    return data[idx];
}

定义一个 const 版本的函数也是有益的:

const char &at(std::size_t idx) const
{
    return data[idx];
}

另请注意 std::size_t 的使用(这是一种保证足够大以表示任何大小的无符号类型)。这样您可以提高可移植性,并且不必检查负索引。

关于C++运算符重载,我自己的字符串类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471392/

相关文章:

c++ - aesimc 指令给出了错误的结果

c++ - 为什么这段代码在 Clang++ 中有效,但在 G++ 中无效?

c++ - 使用复制列表初始化从函数返回,不需要复制/移动构造函数 - 它在 C++ 11 标准中的何处说明?

c++ - std::weak_ptr::operator= 困惑

c++ - 扭曲的位图文件

c++ - 在 Qt 5.2.1 上编写的 SSL 服务器的 SSL 握手失败

c++ - 是否可以重载插入运算符 >> 以在不使用数组的情况下接收用户输入?

python - 在 While 循环中使用随机 Once

string - 为什么多个字符串的最长公共(public)子序列是 NP-Hard?

delphi - dll 调用的奇怪字符串行为