引用和从C++中的运算符返回的常量引用

reference and const reference returned from operator in C++

本文关键字:引用 运算符 返回 常量 C++      更新时间:2023-10-16

我不明白为什么我们通常需要两个返回引用的函数版本——一个是const,另一个不是。例如,在此代码中:

const char& String::operator[](int index) const {
    verify_index(index);
    return data[index];
}
char& String::operator[](int index) {
    verify_index(index);
    return data[index];
}

如果我们只有const,那么我们就不能做例如str[i]=value。但是只有非常数引用有什么问题,有人能举个例子吗?

感谢

如果只有非约束重载,则无法在const字符串上使用[] synax。

void print_first(const std::string& word) {
    std::cout << word[0]; //like this
}

如果只有const重载,则无法使用[]语法修改字符串:

void edit_first(std::string& word) {
    word[0] = 'a';
}

如果您创建了一个返回可变字符的const重载,那就更糟了!

void edit_first(const std::string& word) {
    word[0] = 'a'; //wait, I thought word was const?
}

令人沮丧的是,您必须添加两个重载,但通常90%的代码可以共享(就像您对verify_index所做的那样),或者它们最终只是两个行。

(还有第四个非const重载组合,它返回一个const字符,但这是无害的,而且基本上没有用,所以……是的。)

const String s = "abc";
cout << s[0]; // Ooops! Cannot run operator[] because no const qualifier.

您的示例中有两个const关键字实例,而您似乎忽略了第二个实例,即允许您在const实例上调用运算符的实例。