我有一个类,它引用了另一个结构。
struct DNA { ... };
class Cohort {
private:
DNA& genetics;
...
public:
Cohort(DNA& g) : genetics(g) {}
...
};然后,我得到了Cohorts的向量。
std::vector<Cohort> cohorts;然后,我必须在向量的开头插入队列。
cohorts.insert(cohorts.begin(), Cohort(eggs, genetics)); 我犯了个错误。
error: object of type 'Thor_Lucas_Development::Cohort' cannot be assigned because its copy assignment
operator is implicitly deleted我假设当项目被插入到向量中时,它就被复制进来了。因为我的Cohort类中有一个引用,所以它的复制赋值操作符被隐式删除。
所以..。到底怎么回事?在处理Cohort类时,我不能使用向量吗?或者我必须new向上的Cohort并在向量中有指向它的指针吗?
有点烦人。
发布于 2018-06-25 04:15:05
您可以在适当的位置构造对象:
cohorts.emplace(cohorts.begin(), eggs, genetics); 但是引用成员很少是个好主意--用指针代替。
如果在开头大量插入,您可能需要std::deque而不是std::vector。
发布于 2018-06-25 04:33:32
正如错误消息所述,不能在活动对象中重新绑定引用,这就是为什么默认情况下将删除赋值。
除了在向量中存储指针之外,还可以以某种方式重写类:
使用指针而不是引用。在这个用法中,它们是非常有价值的:
#include <vector>
struct Nyan {
int *x;
};
int main() {
int x;
std::vector<Nyan> v{{&x}, {&x}, {&x}};
v.insert(v.begin(), Nyan{&x});
}(作为参考的替代,普通指针是可以的,但是如果需要的话,可以使用<memory>中定义的任何包装器。)
您甚至可以添加一些保护来不允许空指针:
struct Nyan {
Nyan(int &x): x(&x) {}
private:
int *x;
};II.早在std::reference_wrapper中就引入了C++11,以适应不可再绑定性,允许在容器中存储引用:
#include <vector>
#include <functional>
struct Nyan {
std::reference_wrapper<int> x;
};
int main() {
int x;
std::vector<Nyan> v{{x}, {x}, {x}};
v.insert(v.begin(), Nyan{x});
}https://stackoverflow.com/questions/51015846
复制相似问题