第一种情况:派生类中不使用new
- class baseDMA{
- private:
- char *label;
- int rating;
- public:
- baseDMA(const char *l = nullptr, int r =0);
- baseDMA( const baseDMA &rs);
- virtual ~baseDMA();
- baseDMA & operator=( const baseDMA &rs);
- };
- class lacksDMA : public baseDMA {
- private:
- char color[40];//原书这里有错误,我猜测应该是 long temp; 定义一个长整形。
- public:
- };
派生类直接使用基类的析构函数没有问题。
难点在于理解重载复制构造函数。 如果是long参数的话,那lacksDMA复制的话,temp变量采用常规赋值即可,继承的baseDMA对象则采用基类的复制构造函数。
第二种情况:派生类使用了new
- class lacksDMA : public baseDMA {
- private:
- char *style;
- public:
- };
如下:
- hasDMA::hasDMA(const hasDMA & hs) : baseDMA(hs)
- {
- style = new char[ std::strlen(hs.style)+1];
- std::strcpy(style, hs.style);
- }
- hasDMA & hasDMA::operator=(const hasDMA & hs){
- if (this == &hs) {
- return *this;
- }
- baseDMA::operator=(hs); //赋值基类对象 也是采用动态分配内存 显示调用
- delete []style;
- style = new char[ std::strlen(hs.style)+1];
- std::strcpy(style, hs.style);
- return *this;
- }
- hasDMA::~hasDMA(){
- delete [] style;
- }