const矢量参考过载

const vector reference overloading

本文关键字:参考 const      更新时间:2023-10-16

为简单起见,只需通过代码的一部分即可。

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

我的问题是如何参与超载的const获取方法。当我尝试创建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方法。

由于 myA不是本身 const,因此超载分辨率将有利于非const过载。

那是我恐怕的生活。

如果您想要const版本,则可以在呼叫网站上使用const_cast,甚至可以使用隐式铸件,将myA铸造为const类型:

const A& myA_const = myA;

并使用myA_const,您要调用const过载。

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