继承和动态内存分配(C++ Primer Plus 第十三章)

第一种情况:派生类中不使用new

  1. class baseDMA{  
  2. private:  
  3.     char *label;  
  4.     int rating;  
  5.       
  6. public:  
  7.     baseDMA(const char *l = nullptr, int r =0);  
  8.     baseDMA( const baseDMA &rs);  
  9.       
  10.     virtual ~baseDMA();  
  11.       
  12.     baseDMA & operator=( const  baseDMA &rs);  
  13.       
  14. };  

  1. class lacksDMA : public baseDMA {  
  2. private:  
  3.     char color[40];//原书这里有错误,我猜测应该是  long temp; 定义一个长整形。  
  4.       
  5. public:  
  6. };  
派生类lacksDMA不使用new。

派生类直接使用基类的析构函数没有问题。  

难点在于理解重载复制构造函数。  如果是long参数的话,那lacksDMA复制的话,temp变量采用常规赋值即可,继承的baseDMA对象则采用基类的复制构造函数。

第二种情况:派生类使用了new

  1. class lacksDMA : public baseDMA {  
  2. private:  
  3.     char *style;  
  4.       
  5. public:  
  6. };  
这种情况下,派生类必须定义显示析构函数,复制构造函数和赋值运算符。
如下:
  1. hasDMA::hasDMA(const hasDMA & hs) : baseDMA(hs)  
  2. {  
  3.     style = new char[ std::strlen(hs.style)+1];  
  4.     std::strcpy(style, hs.style);  
  5. }  
  6.   
  7. hasDMA & hasDMA::operator=(const hasDMA & hs){  
  8.     if (this == &hs) {  
  9.         return *this;  
  10.     }  
  11.       
  12.     baseDMA::operator=(hs); //赋值基类对象  也是采用动态分配内存  显示调用  
  13.     delete []style;  
  14.     style = new char[ std::strlen(hs.style)+1];  
  15.     std::strcpy(style, hs.style);  
  16.     return *this;  
  17. }  
  18.   
  19. hasDMA::~hasDMA(){  
  20.     delete [] style;  
  21. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值