类型的非const引用的无效初始化错误

时间:2013-10-04 05:09:56

标签: c++

下面是从字符串中查找和替换子字符串的代码。但是我无法将参数传递给函数。

错误讯息:

  

'std :: string&类型的非const引用的无效初始化{aka std :: basic_string&}'来自'const char *'

类型的右值

请帮助解释

#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;
}

4 个答案:

答案 0 :(得分:6)

一个简单的解释是,由于你的replaceAll函数正在改变一个字符串,你必须给它一个实际的字符串来改变。

int main() {
    string str = "hellounny";
    replaceAll(str,"n","k");
    return 0;
}

答案 1 :(得分:1)

这应该删除错误:

#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() {

    string temp = "hellounny";
    replaceAll(temp,"n","k");
    return 0;
}

答案 2 :(得分:1)

如果您希望能够将临时值作为参数传递,则可以返回结果:

std::string replaceAll(string s, const string &search, const string &replace ) {
    for( size_t pos = 0; ; pos += replace.length() ) {
        pos = result.find( search, pos );
        if( pos == string::npos ) break;
        result.erase( pos, search.length() );
        s.insert( pos, replace );
    }
    return s;
}

std::string result = replaceAll("hellounny", "n", "k");

答案 3 :(得分:0)

您的代码问题在于您尝试使用非常量引用来引用临时对象。编译器创建临时对象以评估表达式以临时存储对象值(用于参数传递,从func返回值等) 。您可以将非常量对象的地址分配给const指针,因为您只是承诺不更改可以更改的内容。 但是您不能将const对象的地址分配给非const引用,因为这将允许您稍后修改该对象。 正确的方法是使用temp变量传递参数

int main()
{
    string temp = "This is a Temperory Var";
    replaceAll(temp,"n","k");
}

as @Umer和@john写了

相关问题