vector and const(向量和常量)
问题描述
考虑一下
void f(vector<const T*>& p)
{
}
int main()
{
vector<T*> nonConstVec;
f(nonConstVec);
}
以下不编译.问题是 vector 不能转换为 vector ,这似乎对我来说不合逻辑,因为存在从 T* 到 const T* 的隐式转换.这是为什么?
The following does not compile.The thing is that vector<T*> can not be converted to vector <const T*> , and that seems illogically to me , because there exists implicit conversion from T* to const T*. Why is this ?
vector 也不能转换为 vector ,但这是意料之中的,因为 const T* 不能隐式转换为 T*.
vector<const T*> can not be converted to vector <T*> too, but that is expected because const T* can not be converted implicitly to T*.
推荐答案
我在您的代码中添加了几行.这足以说明为什么不允许这样做:
I've added a few lines to your code. That's sufficient to make it clear why this is disallowed:
void f(vector<const T*>& p)
{
static const T ct;
p.push_back(&ct); // adds a const T* to nonConstVec !
}
int main()
{
vector<T*> nonConstVec;
f(nonConstVec);
nonConstVec.back()->nonConstFunction();
}
这篇关于向量和常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向量和常量
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
