【发布时间】:2013-04-22 20:02:50
【问题描述】:
我在课堂上有这样的方法。
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 这样的方法来接受非恒定值,但最好将字符串作为 const 传递!
并且因为它被怀疑它不能被编译:
我想知道,我尝试做的事真的好吗?
以及如何将 const 字符串转换为字符串? (我尝试使用 C 风格转换或 const_cast - 没有成功)。
提前致谢!
【问题讨论】: