【发布时间】:2013-10-11 00:08:45
【问题描述】:
以下是从字符串中查找和替换子字符串的代码。但我无法将参数传递给函数。
错误信息:
从“const char*”类型的右值初始化“std::string& {aka std::basic_string&}”类型的非常量引用无效
请帮忙解释一下
#include <iostream>
#include <string>
using namespace std;
void replaceAll( string &s, const string &search, const string &replace ) {
for( size_t pos = 0; ; pos += replace.length() ) {
pos = s.find( search, pos );
if( pos == string::npos ) break;
s.erase( pos, search.length() );
s.insert( pos, replace );
}
}
int main() {
replaceAll("hellounny","n","k");
return 0;
}
【问题讨论】:
-
您不能将临时对象绑定到非常量引用。它应该改变什么?
-
当然是临时的。我从来没有真正同意这条规则,但我曾经收到 Bjarne Stroustrup 本人的回复,他说他觉得允许代码像这样修改临时变量“太混乱”。
标签: c++