2013-04-22 146 views
1

我在类中有这样的方法。通过引用传递const值的C++

Word Sentence::parse_word(std::string &word) { 
} 

一切工作正常。 经过一番考虑后,我得出结论,这是不好的。 因为在这个方法里面,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 */ 
    } 

即我不改变这个方法中的那个字符串。
我知道我在这里使用find等方法来接受非包含值,但最好是将string作为const来传递!

,并因为它的怀疑也不能因为它编译: enter image description here

我不知道,是它在所有好的东西我尝试做?
如何将const字符串转换为字符串? (我尝试使用C风格的转型或const_cast - 没有成功)。

在此先感谢!

回答

9

您应该使用的const_iterator代替iterator,因为你是通过引用调用begin()const

string::const_iterator iter1 = word.begin(); 
//  ^^^^^^ 

与标准集装箱的接口协议,std::string defines two overloads of the begin() member function:非const合格一个返回一个std::string::iterator和一个const - 合格返回const_iterator

由于正在通过引用调用begin()const,后者过载返回const_iterator被拾取(非const一个显然是不可行的)。

这就是为什么编译器会拒绝编译上面的例子。在C++ 11,你可以通过使用auto避免了这样的烦恼:

auto iter1 = word.begin(); 
4

如果传递const string或引用const string,你需要使用一个const_iterator

string::const_iterator iter1= word.begin();