【发布时间】: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