2014-03-13 64 views
0

我正在通过一些例子看,我似乎无法看到为什么字符串替换功能不工作。我使用的Visual C++ 2010C++ - string.replace不工作

的代码我试图编译行是:

string MyClass::replacestr (const string &input){ 

    string subString = "str"; 
    string subString2 = "STR"; 

    for(int index = input.find(subString); index != string::npos; index = input.find(subString, index +subString.length())) 
    { 
     input.replace(index, 2, subString2); 
    } 

} 

它给了我这个错误在Visual Studio:

3 IntelliSense: no instance of overloaded function "std::basic_string<_Elem, _Traits, _Ax>::replace [with _Elem=char, _Traits=std::char_traits<char>, _Ax=std::allocator<char>]" matches the argument list and object (the object has type qualifiers that prevent a match) c:\..test.cpp 36 Test 

我只是不明白为什么它不会按照它在C++ refernce网站上解释的方式工作。

回答

2

字符串替换改变了字符串的内容。你的字符串被标记为const。这意味着你不能在它上面调用replace。

+0

耶稣,这是漫长的一天。谢谢回复。 –

2

替换修改字符串的内容(是非常量成员函数)。您正在传递一个const对该函数的引用。这就是为什么替换给你错误。

您不能在const对象上调用非const成员函数。


虽然错误信息可能已经更清楚了。