| 编程中国 | 业界新闻 | 技术文章 | 视频教程 | 下载频道 | 程序源码 | 个人空间 | 编程论坛
全能ASP/PHP/ASP.NET主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付买域名,送MP3、MP4
高端软件开发 = 年薪十万不是梦赛孚耐:软件保护加密专家身份认证令牌USB KEY买空间,免费送域名(厦门中资源)
共有 157 人关注过本帖
标题:派生类的赋值重载操作符需要和基类的一样先清除指针成员内存在开辟新空间赋 ...
收藏  订阅  推荐  打印 
沿途有鬼
Rank: 2
等级:注册会员
帖子:68
积分:882
注册:2008-7-20
派生类的赋值重载操作符需要和基类的一样先清除指针成员内存在开辟新空间赋值吗?

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();
}

[ 本帖最后由 沿途有鬼 于 2008-8-17 12:54 编辑 ]
搜索更多相关主题的帖子: 操作符  赋值  基类  派生类  指针  
2008-8-17 12:03
关于我们 | 广告合作 | 编程中国 | 清除Cookies | Archiver | WAP | TOP

编程中国 版权所有,并保留所有权利。鲁ICP备08000592号
Powered by Discuz, Processed in 0.051002 second(s), 9 queries.
Copyright©2004-2008, BCCN.NET, All Rights Reserved