【问题标题】:c++ passing const value by referencec++ 通过引用传递 const 值
【发布时间】: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 - 没有成功)。

提前致谢!

【问题讨论】:

    标签: c++ stl constants


    【解决方案1】:

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

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

    与标准容器的接口一致,std::string defines two overloads of the begin() member function:一个非const 限定返回一个std::string::iterator,一个const 限定一个返回一个const_iterator

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

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

    auto iter1 = word.begin();
    

    【讨论】:

      【解决方案2】:

      如果传递const string 或引用const string,则需要使用const_iterator

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

      【讨论】:

        猜你喜欢
        • 2012-06-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多