为了简单起见,只需传递代码的一部分。
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方法。