replace函数传递常量和非常量参数的问题

mhzzzz 2016-11-04 02:46:23
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;
using std::prev;

void Replace(string& s, string const& oldVal, string const& newVal)
{
for (string::size_type i = 0; i != s.size(); ++i)
if (s.substr(i, oldVal.size()) == oldVal) {
s.replace(i, oldVal.size(), newVal);
i += newVal.size() - 1;
}
}

int main()
{
string str{"To drive straight thru is a foolish, tho courageous act."};
Replace(str, "tho", "though");
Replace(str, "thru", "through");
cout << str << endl;
}

如以上代码,如果函数定义时,为void Replace(string& s, string& oldVal, string& newVal),
调用函数Replace(str, "tho", "though");
Replace(str, "thru", "through");
运行
DEVC++编译器会报错:无效的非常量引用初始化。
这是为什么
...全文
186 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
paschen 2016-11-04
  • 打赏
  • 举报
回复
因为你的参数"tho" "though" 不是string类型 参数在传递时会隐式转换成一个临时的string类型变量,这是个临时变量,不能绑定左值引用
jiqiang01234 2016-11-04
  • 打赏
  • 举报
回复
使用algorithm头文件中的replace,直接就能完成你要的功能

33,317

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧