首页 文章

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

提问于
浏览
5

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

错误信息 :

从'const char *'类型的右值开始无效初始化'std :: string&{aka std :: basic_string&}'类型的非const引用

请帮忙解释一下

#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

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

    int main() {
        string str = "hellounny";
        replaceAll(str,"n","k");
        return 0;
    }
    
  • 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;
    }
    
  • 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");
    
  • 6

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

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

    正如@Umer和@john写的那样

相关问题