注册 登录
编程论坛 C++教室

派生类的赋值重载操作符需要和基类的一样先清除指针成员内存在开辟新空间赋值吗?

沿途有鬼 发布于 2008-08-17 12:03, 650 次点击
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;
}

#include<iostream>
using namespace std;
#include"cd.h"
void Bravo(const Cd & disk);
int main()
{
    Cd c1("Beatles","Capitol",14,35.5);
    Classic c2=Classic("Piano Sonata in B flat,Fantasia in C",
        "Alfred Brendel","Philips",2,57.17);

    Cd * pcd=&c1;

    cout<<"Using object directly: \n";
    c1.Report();
    c2.Report();

    cout<<"Using type cd * pointer to objects: \n";
    pcd->Report();
    pcd=&c2;
    pcd->Report();

    cout<<"Calling a function with a Cd reference argument: \n";
    Bravo(c1);
    Bravo(c2);
    cout<<"Testing assignment: ";
    Classic copy;
    copy=c2;//对应那个delete [] musicstr;需要加delete [] musicstr;这样做吗?
    copy.Report();

    return 0;
}

void Bravo(const Cd & disk)
{
    disk.Report();
}

[[it] 本帖最后由 沿途有鬼 于 2008-8-17 12:54 编辑 [/it]]
0 回复
1