const矢量参考过载
const vector reference overloading
为简单起见,只需通过代码的一部分即可。
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 上进行了测试。
相关文章:
- 不能使这种类型的"void(C::* volatile)(int) const "在参考手册C++示
- I/O 操纵器错误或临时延长寿命由 const 参考?
- RVALUE参考与const lVALUE参考作为参数之间的混淆
- 为什么const rvalue合格的std ::可选:: value()返回const rvalue参考
- 转发模板参数的const-度,我应该使用转发参考
- 如何检查两种类型是否相同,忽略const和参考
- 基于范围的循环中的const参考不起作用
- const自动参考绑定到(NULL)指针 - 实际类型是什么
- "const"会取消通用参考的资格吗?
- 重新分配到const参考
- 通过参考const成员通过参考时,尝试引用已删除的函数
- 人们为什么写私人场getters返回非const参考
- 为什么删除字符串迭代器会产生const char参考
- 从C 模板中的非const l值参考中推导const l值参考
- 如何使用参考const对象传递到函数作为参数
- 从const函数返回非const属性参考
- 一种体面的方式来转换const列表参考参数,然后传递到另一个函数
- const参考的不同风味
- C 接收const lvalue和rvalue参考参数,而无需过载
- 通过STD :: Chrono ::按价值或参考const的持续时间