为什么我不能做一个引用的向量? [英] Why can't I make a vector of references?
问题描述
当我这样做:
std::vector<int> hello;
一切都很棒。但是,当我使它成为引用的向量时:
Everything works great. However, when I make it a vector of references instead:
std::vector<int &> hello;
我得到了可怕的错误,如error C2528:'pointer':指向引用的指针是非法的。
I get horrible errors like "error C2528: 'pointer' : pointer to reference is illegal".
我想把一堆structs的引用放到一个向量中,这样我就不用再去处理指针了。为什么矢量引起这样的发脾气?
I want to put a bunch of references to structs into a vector, so that I don't have to meddle with pointers. Why is vector throwing a tantrum about this? Is my only option to use a vector of pointers instead?
推荐答案
向量的容器的组件类型必须 可分配
。引用是不可分配的(你只能在声明它们时将它们初始化一次,并且不能让它们稍后引用其他引用)。其他不可分配类型也不允许作为容器的组件,例如向量< const int>
不允许。
The component type of containers like vectors must be Assignable
. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int>
is not allowed.
这篇关于为什么我不能做一个引用的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!