【问题标题】:const vector reference overloadingconst 向量引用重载
【发布时间】:2017-09-22 07:46:06
【问题描述】:

为简单起见,只需传递部分代码。

class A {
public:
std::vector<int> & get(){ return myVector;}
const std::vector<int> & get() const {return myVector;}
private:
   std::vector<int> myVector;
}

我的问题是如何涉及重载的 const get 方法。当我尝试创建 const_iterator 和调试代码时,它涉及非常量方法。 想了解它是如何工作的我使用以下sn-ps

A myA;
myA.get().push_back(1);
for (const auto& v: myA.get()) { } // it involve not const get method

std::vector<int>::const_iterator cit = myA.get().begin()
//it involves not const method

 const std::vector< int > v = myA.get( );
 // involves non-const method

甚至我创建函数:

int constVector( const std::vector< int > &constVector )
{
   return constVector[0];
}

int b = constVector( myA.get( ) ); // it involves non-const method

如果不涉及,重载 const 方法的目的是什么。

以及我做错了什么以及如何使用 const 方法。

【问题讨论】:

  • 当 A 的引用为 const 时,调用 const 方法

标签: c++ constants overloading


【解决方案1】:

由于myA 不是自身 const,重载决议将有利于非const 重载。

这就是我害怕的生活。

如果您想要const 版本,那么您可以在调用站点使用const_cast,甚至是隐式转换,将myA 转换为const 类型:

const A& myA_const = myA;

并在您希望调用 const 重载的地方使用 myA_const

【讨论】:

  • 我来不及回答,但您可以添加我在 ideone 上准备的 MCVE。
  • @Scheff:你为什么认为你来晚了?你用那个链接回答,我会投票。如果有多个答案可供选择,那么 SO 效果最好。
【解决方案2】:

我获取了 OP 的代码片段并制作了一个 MCVE,它演示了 Bathsheba 描述的内容:

#include <iostream>
#include <vector>

class A {
  public:
    std::vector<int>& get()
    {
      std::cout << "A::get()" << std::endl;
      return myVector;
    }
    const std::vector<int>& get() const
    {
      std::cout << "A::get() const" << std::endl;
      return myVector;
    }

  private:
    std::vector<int> myVector;
};

int main()
{
  A myA;
  myA.get().push_back(1);
  for (const auto& v: myA.get()) { } // it involve not const get method
  // use const reference to instance
  std::cout << "use const reference to instance" << std::endl;
  { const A &myAC = myA;
    for (const auto& v: myAC.get()) { } // it involves const get method
  }
  return 0;
}

输出:

A::get()
A::get()
use const reference to instance
A::get() const

ideone 上测试。

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多