标题:派生类的赋值重载操作符需要和基类的一样先清除指针成员内存在开辟新空间赋 ...
只看楼主
沿途有鬼
Rank: 1
等 级:新手上路
帖 子:68
专家分:0
注 册:2008-7-20
 问题点数:0 回复次数:0 
派生类的赋值重载操作符需要和基类的一样先清除指针成员内存在开辟新空间赋值吗?
class Cd
{
private:
    char * performers;
    char * label;
    int selections;
    double playtime;
public:
    Cd(const char * s1,const char * s2,int n,double x);
    Cd(const Cd & d);
    Cd();
    ~Cd();
   virtual void Report()const;
    Cd & operator=(const Cd & d);
};

class Classic: public Cd
{
private:
    char * musicstr;

public:
    Classic(const char * mu="none",const char * s1="null name",const char * s2="null label",int n=0,double x=0.0);
    Classic(const char * mu,const Cd & c);
    Classic(const Classic & s);
    Classic & operator=(const Classic & s);

    ~Classic();
     virtual void Report()const;
};

Cd & Cd::operator=(const Cd & d)
{
    if(this==&d)
        return *this;
    delete [] performers;//1
    delete [] label;//2
    performers=new char[strlen(d.performers)+1];
    label=new char[strlen(d.label)+1];
    strcpy(performers,d.performers);
    strcpy(label,d.label);
    selections=d.selections;
    playtime=d.playtime;
    return *this;
}


Classic & Classic::operator=(const Classic & s)
{
    if(this==&s)
        return *this;
   
    Cd::operator =(s);
         delete [] musicstr;//需要和//1、//2一样删除之前的指针成员内存后在分配空间吗?                                 
    musicstr=new char[strlen(s.musicstr)+1];
    strcpy(musicstr,s.musicstr);
    return *this;
}

[[it] 本帖最后由 沿途有鬼 于 2008-8-17 12:21 编辑 [/it]]
搜索更多相关主题的帖子: 操作符 赋值 基类 派生类 指针 
2008-08-17 12:03



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-228673-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.124732 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved