const向量引用重载

时间:2017-09-22 07:46:06

标签: c++ const overloading

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

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和调试代码时,它涉及非const方法。 想了解它是如何工作的我使用以下代码段

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方法。

2 个答案:

答案 0 :(得分:8)

由于myA不是本身 const,因此重载解析会支持非const重载。

这就是我害怕的生活。

如果您需要const版本,则可以在调用网站上使用const_cast,甚至可以使用隐式广告,将myA转换为const类型:

const A& myA_const = myA;

并使用myA_const来调用const重载。

答案 1 :(得分:5)

我拿了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上进行了测试。

相关问题