pZC*_*ZCZ 3 c++ overloading const
为简单起见,只需传递部分代码即可.
class A {
public:
std::vector<int> & get(){ return myVector;}
const std::vector<int> & get() const {return myVector;}
private:
std::vector<int> myVector;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何涉及重载的const get方法.当我尝试创建const_iterator和调试代码时,它涉及非const方法.想要了解它的工作原理我使用以下代码段
A myA;
myA.get().push_back(1);
for (const auto& v: myA.get()) { } // it involve not const get method
Run Code Online (Sandbox Code Playgroud)
要么
std::vector<int>::const_iterator cit = myA.get().begin()
//it involves not const method
Run Code Online (Sandbox Code Playgroud)
要么
const std::vector< int > v = myA.get( );
// involves non-const method
Run Code Online (Sandbox Code Playgroud)
甚至我创建功能:
int constVector( const std::vector< int > &constVector )
{
return constVector[0];
}
int b = constVector( myA.get( ) ); // it involves non-const method
Run Code Online (Sandbox Code Playgroud)
如果不涉及重载const方法,那么它的目的是什么?
我做错了什么以及我如何涉及const方法.
由于myA不是自身 const,过载解决方案将有利于非const过载.
这就是我害怕的生活.
如果你想要const版本,那么你可以const_cast在调用站点使用,或者甚至是隐式转换,以将其myA转换为const类型:
const A& myA_const = myA;
Run Code Online (Sandbox Code Playgroud)
并使用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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
A::get()
A::get()
use const reference to instance
A::get() const
Run Code Online (Sandbox Code Playgroud)
在ideone上测试.