派生类的赋值重载操作符需要和基类的一样先清除指针成员内存在开辟新空间赋值吗?
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]]