复制派生类的构造方法

sam*_*sam 5 c++ inheritance copy-constructor c++11

我有一个基础课

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();

  };
Run Code Online (Sandbox Code Playgroud)

这是由另一个类派生的。

   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);  
  };
Run Code Online (Sandbox Code Playgroud)

这是Derived类的副本构造函数。

SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key) : Keyframebase( 
 key )
       {
        this->x = key.x;
        this->y = key.y;
        this->z = key.z;
       } 
Run Code Online (Sandbox Code Playgroud)

因为我想在复制派生类的对象时也复制基类成员,所以这是将派生类对象作为基类参数的正确方法。

rob*_*oke 5

这是将派生类对象作为基类参数的正确方法吗?

正确。

SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key)
   : Keyframebase( key )  ///<<< Call the base class copy constructor
Run Code Online (Sandbox Code Playgroud)


Mur*_*nik 2

总之,是的。派生类应该必须处理复制基类属性的逻辑,但将该责任委托给基类,作为正确封装的行为。