本文介绍了矢量和const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void f(vector<const T*>& p)
{
}
int main()
{
vector<T*> nonConstVec;
f(nonConstVec);
}
不能转换为向量< const T *>
从 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 ?
向量< const T *>
不能转换为向量< T *>
,但是这是预期的,因为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();
}
这篇关于矢量和const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!