引用和从C++中的运算符返回的常量引用
reference and const reference returned from operator in C++
我不明白为什么我们通常需要两个返回引用的函数版本——一个是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
实例上调用运算符的实例。
相关文章:
- 取消引用运算符不能重载
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 为什么在函数名称中使用取消引用" * "运算符?
- C++:类类型引用运算符=用法
- 为什么通过通用引用运算符 (&&) 将变量的引用传递给 Varadic 模板函数失败?
- 当取消引用运算符 (*) 重载时,*this 的使用是否受到影响?
- 为什么 C++ 中指向方法取消引用运算符的指针具有如此低的优先级
- 赋值不起作用,但带有取消引用运算符的地址起作用?
- 关于解引用运算符是否在表达式中产生对象对值的定义不明确
- 如何重载箭头取消引用运算符->() 不是针对实体对象,而是针对指针
- (取消)引用运算符的评估
- 重载取消引用运算符(运算符*())
- 如何重载取消引用运算符
- 结构引用和取消引用运算符
- 输入迭代器必须具有常量解引用运算符吗
- 对 std::atomic::load 的结果使用结构取消引用 (->) 运算符是否安全
- C++使用引用运算符传递数组
- 使用引用和取消引用运算符读取代码行时遇到问题
- 在C++向量中使用解引用运算符
- 是否可以根据基于的范围类型调用不同的取消引用运算符重载