C++中操作符返回的引用和const引用
我不明白为什么我们通常需要两个返回引用的函数版本——一个是const,另一个不是。 例如,在本代码中:C++中操作符返回的引用和const引用,c++,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 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。但是,只有非常量引用有什么问题,有人能举个例子吗
谢谢如果您只有一个非常量重载,您将无法在常量字符串上使用[]synax 如果你让一个const重载返回一个可变字符,那就更糟糕了
void edit_first(const std::string& word) {
word[0] = 'a'; //wait, I thought word was const?
}
令人沮丧的是,您必须添加两个重载,但通常90%的代码可以像使用verify_index那样共享,或者它们最终只是两个行程序
还有第四个非常量重载组合,返回常量字符,但这是无害的,而且大部分是无用的,所以。。。是的。如果您只有一个非常量重载,您将无法在常量字符串上使用[]synax 如果你让一个const重载返回一个可变字符,那就更糟糕了
void edit_first(const std::string& word) {
word[0] = 'a'; //wait, I thought word was const?
}
令人沮丧的是,您必须添加两个重载,但通常90%的代码可以像使用verify_index那样共享,或者它们最终只是两个行程序
还有第四个非常量重载组合,返回常量字符,但这是无害的,而且大部分是无用的,所以。。。是的。在您的示例中有两个const关键字实例,您似乎忽略了第二个实例,即允许您在const实例上调用运算符的实例。在您的示例中有两个const关键字实例,您似乎忽略了第二个实例,允许您在常量实例上调用运算符的一个
void edit_first(std::string& word) {
word[0] = 'a';
}
void edit_first(const std::string& word) {
word[0] = 'a'; //wait, I thought word was const?
}