我有以下构成:
PropertyCollection
{
private:
Dataset & dataset;
public:
PropertyCollection(Dataset & _dataset) : dataset(_dataset) {}
我需要vector<PropertyCollection> properties
。我需要能够拨打properties.resize(10, PropertyCollection(dataset));
不幸的是,向量需要默认构造函数PropertyCollection::PropertyCollection()
来默认初始化其元素。换句话说,它必须在PropertyCollection::PropertyCollection()
时调用resize
。因此,我相信为了在调用resize
时初始化我的向量属性,我需要实现一个默认构造函数和一个复制赋值运算符。
PropertyCollection
{
private:
Dataset & dataset;
public:
PropertyCollection() = default;
PropertyCollection(Dataset & _dataset) : dataset(_dataset) {}
PropertyCollection & operator=(const PropertyCollection & other)
{
dataset = other.dataset
// error, cannot reassign a reference
不幸的是,我编写复制赋值运算符的尝试失败了。我们无法重新分配参考。那么,我可以做些什么来让我的矢量工作?
为了扩展我的问题,这是其他人一直在努力解决的问题吗? (向量很难处理,因为它在100%的时间都使用默认构造函数)
答案 0 :(得分:0)
我不会使用参考成员。
如果您的PropertyCollection
实例“拥有”Dataset
,那么请将Dataset
作为拥有类的普通成员并完成它。你的课应该是这样的:
PropertyCollection
{
private:
Dataset dataset;
public:
// NOTE: single-argument ctors should be made explicit
// NOTE: and the formal parameter should be const ref
explicit PropertyCollection(const Dataset& _dataset) : dataset(_dataset) {}
// ...etc etc, other ctors, ...
};
如果Dataset
实例在多个包含对象中共享,则使用共享指针表示共享所有权:std::shared_ptr<T>
如果使用C ++ 11 - 兼容编译器,否则为Boost smart pointer template。我只是为了完整性而提到这一点,因为我怀疑你没有这个用例。