gpt4 book ai didi

C++通过引用传递常量值

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:13:16 25 4
gpt4 key购买 nike

我在类里面有这样的方法。

 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 这样接受非连续值的方法,但最好将字符串作为常量传递!

并且因为它怀疑它不能被编译: enter image description here

我想知道,我尝试做的事情真的好吗?
以及如何将 const 字符串转换为字符串? (我尝试使用 C 风格的转换或 const_cast - 但没有成功)。

提前致谢!

最佳答案

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

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

与标准容器接口(interface)一致, 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();

关于C++通过引用传递常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com