c ++通过引用传递const值

Teb*_*ebe 1 c++ stl const

我在课堂上有这样的方法.

 Word Sentence::parse_word(std::string &word) {
 }
Run Code Online (Sandbox Code Playgroud)

一切正常.经过一些考虑后,我得出的结论是,这并不好.因为这个方法里面std::string word没有改变.
所以最好传递它const std::string &word以使方法的使用更加明显和清晰.

此外,拥有这种签名的方法我不可能称之为parse_word(string("some_text))-

所以我决定将签名更改为:

Word Sentence::parse_word( const string &word) {
    string::iterator iter1= word.begin();
    iter1=find( word.begin(),word.end(),'/');
      /*some other code */
  }
Run Code Online (Sandbox Code Playgroud)

即我不在此方法中更改该字符串.
我知道我在这里使用像find这样的方法接受非常规值,但最好将字符串作为const传递!

因为它被怀疑无法编译因为它: 在此输入图像描述

我想知道,我尝试做的一切都很好吗?
如何将const字符串转换为字符串?(我尝试使用C风格的转换或const_cast - 没有成功).

提前致谢!

And*_*owl 9

您应该使用a const_iterator而不是iterator,因为您begin()通过引用调用const:

string::const_iterator iter1 = word.begin();
//      ^^^^^^
Run Code Online (Sandbox Code Playgroud)

与标准容器的接口一致,std::string定义了begin()成员函数的两个重载:一个const返回a 的非限定的重载std::string::iterator,以及一个返回一个的const限定的重载const_iterator.

由于您begin()通过引用调用const,因此选择后一个重载返回a const_iterator(非const一个显然不可行).

这就是编译器拒绝编译上面例子的原因.在C++ 11中,你可以使用以下方法避免这种麻烦auto:

auto iter1 = word.begin();
Run Code Online (Sandbox Code Playgroud)