c ++构造函数传递对基础class对象的引用
c++ constructor pass a reference to a base class object
我正在尝试了解复制构造函数。在下面的构造函数定义中,class DataModel
派生自 ComputationModel
。
我的问题是,当您将对基 class 的引用传递给派生 class 的构造函数时,这是一个复制构造函数吗?
为什么默认的复制构造函数在这里不够用?
class DataModel : public ComputationModel {
public:
DataModel(const ComputationalModel &other);
//..
};
mv::DataModel::DataModel(const ComputationModel &other) :
ComputationModel(other)
{}
从技术上讲,您可以定义 DataModel
的复制构造函数,将 ComputationalModel
引用作为函数参数。
DataModel d1(/* Parameter... */);
ComputationModel c1(/* Parameter... */);
DataModel d2(d1); // copy-construct instance, d1 passed as refence to the base class
DataModel d3(c1); // same behavior
然而,这几乎不是一个好主意,因为对象的复制构造通常需要从中复制对象的状态。当您传递基 class 引用时,您会删除派生 class 实例的所有数据成员,这会使新创建的对象处于客户端代码难以猜测的状态。
默认复制构造函数有一个完全相同类型的 const 限定引用参数,在您的例子中:
DataModel(const DataModel& other) = default;
这让我想到你的最后一个问题
Why would the default copy constructor not be sufficent here?
如果不查看您的继承层次结构的其余部分,很难说清楚这一点。一个准则是:如果层次结构中所有数据成员的复制构造函数做正确的事情,那么默认的复制构造函数也做正确的事情。
我正在尝试了解复制构造函数。在下面的构造函数定义中,class DataModel
派生自 ComputationModel
。
我的问题是,当您将对基 class 的引用传递给派生 class 的构造函数时,这是一个复制构造函数吗?
为什么默认的复制构造函数在这里不够用?
class DataModel : public ComputationModel {
public:
DataModel(const ComputationalModel &other);
//..
};
mv::DataModel::DataModel(const ComputationModel &other) :
ComputationModel(other)
{}
从技术上讲,您可以定义 DataModel
的复制构造函数,将 ComputationalModel
引用作为函数参数。
DataModel d1(/* Parameter... */);
ComputationModel c1(/* Parameter... */);
DataModel d2(d1); // copy-construct instance, d1 passed as refence to the base class
DataModel d3(c1); // same behavior
然而,这几乎不是一个好主意,因为对象的复制构造通常需要从中复制对象的状态。当您传递基 class 引用时,您会删除派生 class 实例的所有数据成员,这会使新创建的对象处于客户端代码难以猜测的状态。
默认复制构造函数有一个完全相同类型的 const 限定引用参数,在您的例子中:
DataModel(const DataModel& other) = default;
这让我想到你的最后一个问题
Why would the default copy constructor not be sufficent here?
如果不查看您的继承层次结构的其余部分,很难说清楚这一点。一个准则是:如果层次结构中所有数据成员的复制构造函数做正确的事情,那么默认的复制构造函数也做正确的事情。