c++ - [] 的运算符重载

标签 c++ overloading operator-keyword

所以我尝试了 [] 的运算符重载,但它不起作用。 我创建了这个类:

class String
{
private:
    char* str;
public:
    String(char* str) // constructor
    {
        this->str = str;
    }
    char* Val() // returns value of this.str
    {
        return this->str;
        }
char & operator [](int index) { return this->str[index]; }
};

我试着像这样使用它

String* str = new String("example");
cout << str[2] << endl;

预期的结果是字母“a”的打印,但它不会工作.. 虽然当我像这样创建一个对象时它确实有效:

String str("example");
cout << str[2] << endl;

有什么建议吗?

最佳答案

String* str = new String("example");
cout << str[2] << endl;

这里 str 是一个指针,所以 str[2] 不是在调用你的运算符,而是从地址 str 不存在,因此您有未定义的行为。

你需要的是:

cout << (*str)[2] << endl;

关于c++ - [] 的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34963885/

相关文章:

c++ - C++ 中的重载解析

C++ 模板/ostream 运算符问题

c++ - 如何制作 CMake 模块

c++ - 如何在 std::function 的签名上重载构造函数?

c++ - 在它所在的类之外声明一个嵌套类?

javascript - node.js - 重载函数

C++运算符重载——指针、乘法

c++ - C++ 集合中的迭代器

c++ - 用函数返回值初始化一个 std::string,有拷贝吗?