所以我尝试了 [] 的运算符重载,但它不起作用。 我创建了这个类:
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/