派生 class 的复制构造函数

Copy Constructor for derived class

我有一个基地class

class Keyframebase
  {

    private:
std::string stdstrName;
float time;
KeyframeType keyframeType;

    public:
Keyframebase();
Keyframebase(KeyframeType keyType);
Keyframebase(const Keyframebase &key);
Keyframebase& operator = (const Keyframebase &key);
std::string getName();

  };

由另一个class导出。

   class SumKeyframeXYZ : public Keyframebase
      {
         private:
float x; 
float y;
float z;

          public:
SumKeyframeXYZ();
SumKeyframeXYZ(float x, float y, float z);
SumKeyframeXYZ(const SumKeyframeXYZ& key);
//  const Sum_Position& operator=(const Container& container);
SumKeyframeXYZ& operator=(const SumKeyframeXYZ& key);
void setValue(float x, float y, float z);  
  };

这是 Derived class 的复制构造函数。

SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key) : Keyframebase( 
 key )
       {
        this->x = key.x;
        this->y = key.y;
        this->z = key.z;
       } 

因为我想在复制派生 class 的对象时也复制 Base class 成员,所以这是将派生 class 对象作为参数传递给 base 的正确方法吗class。

so is this the correct approach of giving a derived class object as argument to base class.

正确。

SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key)
   : Keyframebase( key )  ///<<< Call the base class copy constructor

一句话,是的。派生的 class 应该必须处理复制基础 class' 属性的逻辑,但将这一责任委托给基础 class,作为适当封装的行为。

so is this the correct approach

有点像。另请参见 Effective C++ ("Copy all parts of an object") 中的第 12 条,其中作者给出了一个非常相似的示例。

但是,请注意,如果可以的话,通常最好使用特殊成员函数的 compiler-generated 默认版本(假设 KeyframeType 是可复制的,并且复制一个实例是正确的)。在你的情况下,你似乎可以。每当 member-wise 所有数据成员的副本都可以时,只需使用

SumKeyframeXYZ(const SumKeyframeXYZ&) = default;

在您的 class 定义中是要走的路。您也可以省略它,但并不是说 rule of five 实际上要求您明确说明您的特殊成员的 defaultness,即所有成员(当您拥有 virtual 你的基础中的析构函数 class).

is this the correct approach of giving a derived class object as argument to base class

是的,是的。

或者您可以申请 explicitly-defaulted function definition 这种情况,例如

SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key) = default;

compiler-generated 复制构造函数与

做同样的事情
SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key) : Keyframebase(key), 
                                                            x(key.x), 
                                                            y(key.y), 
                                                            z(key.z) 
{}