【发布时间】:2019-07-24 06:41:30
【问题描述】:
我有一个基类
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 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 类的复制构造函数。
SumKeyframeXYZ::SumKeyframeXYZ(const SumKeyframeXYZ& key) : Keyframebase(
key )
{
this->x = key.x;
this->y = key.y;
this->z = key.z;
}
因为当我复制派生类的对象时我也想复制基类成员,所以这是将派生类对象作为参数提供给基类的正确方法。
【问题讨论】:
-
您还应该删除
this->x = key.x等并将其替换为适当的成员初始化习惯用法: Keyframebase(key), x(key.x)等`。
标签: c++ c++11 inheritance copy-constructor