[英]How do I store and add links to a vector of references in C++?
I have a situation in which I have an object of Class1 and a vector of objects of Class2. 我遇到的情况是我有一个Class1对象和一个Class2对象向量。 My goal is to have the object of Class1 contain references to certain objects in the vector of Class2.
我的目标是让Class1的对象包含对Class2的向量中某些对象的引用。 Class1 contains the members:
Class1包含以下成员:
std::vector<Class2&> links;
void addLink(Class2 &obj)
{
links.push_back(obj)
}
I then want to iterate through the objects of Class2 and for any objects which meet a certain condition, I want to add a link like so: 然后,我想遍历Class2的对象,对于满足一定条件的任何对象,我想添加一个链接,如下所示:
for (std::vector<Class2&>::iterator i = vector2.begin(); i != vector2.end(); ++i)
{
if (condition_satisfied(*i))
{
obj1.addLink(*i)
}
}
However, doing this gives me compile-time errors of C2528: pointer to reference is illegal. 但是,这样做给了我C2528的编译时错误:引用指针是非法的。 What am I doing wrong here?
我在这里做错了什么?
std::vector<T>
requires T
to be CopyAssignable in C++98, Eraseable in C++11, but a plain reference is neither. std::vector<T>
需要T
是CopyAssignable在C ++ 98, 可擦除在C ++ 11,但一个普通的参考两者都不是。 In other words, references cannot be stored in std::vector
. 换句话说,引用不能存储在
std::vector
。
You may like to use plain pointers instead. 您可能希望改用普通指针。 Or
std::reference_wrapper<T>
, which is a pointer in disguise. 或
std::reference_wrapper<T>
,这是伪装的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.