指针内存问题

本文深入探讨了C++中深拷贝与浅拷贝的概念,通过具体的Cd和Classic类实例,详细解释了如何正确实现深拷贝以避免指针问题。文章分析了构造函数、析构函数、赋值运算符重载和复制构造函数在管理动态分配内存时的重要性。

 

为什么使用注释的语句会发生指针问题呢?

 

#include<iostream>
#include"13.2.h"
#include<cstring>
#pragma warning(disable:4996)
using namespace std;
Cd::Cd(char *s1, char *s2, int n, double x)
{
    performers = new char[strlen(s1)+1];
    strcpy(performers, s1);
    label = new char[strlen(s2) + 1];
    strcpy(label, s2);
    selections = n;
    playtime = x;
}
Cd::Cd(const Cd & d)
{
    /*Cd(d.performers, d.label, d.selections, d.playtime);*/
    performers = new char[strlen(d.performers) + 1];
    strcpy(performers, d.performers);
    label = new char[strlen(d.label) + 1];
    strcpy(label, d.label);
    selections = d.selections;
    playtime = d.playtime;
}
Cd::Cd()
{
    performers = new char[1];
    performers =nullptr ;
    label = new char[1];
    label[0] = '\0';
    selections = 0;
    playtime = 0;
}
Cd::~Cd()
{
    delete[] label;
    delete[] performers;
}
void Cd::Report() const
{
    cout << "performers:" << performers << endl;
    cout << "label:" << label << endl;
    cout << "number of selections:" << selections << endl;
    cout << "playing time in minutes:" << playtime << endl;
    cout << endl;
}
Cd & Cd::operator=(const Cd & d)
{
    if (this == &d)
        return *this;
    delete[] performers;
    delete[] label;
    //Cd(d.performers, d.label, d.selections, d.playtime);
    performers = new char[strlen(d.performers) + 1];
    strcpy(performers, d.performers);
    label = new char[strlen(d.label) + 1];
    strcpy(label, d.label);
    selections = d.selections;
    playtime = d.playtime;
    return *this;
}
Classic::Classic(char * s1, char * s2, char * s3, int n, double x) :Cd(s2, s3, n, x)
{
    //Cd::Cd(s2, s3, n, x);
    name = new char[strlen(s1) + 1];
    strcpy(name, s1);
}
Classic::Classic(const Classic & d, char * c) :Cd(d)
{
    //Cd::Cd(d);
    name = new char[strlen(c) + 1];
    strcpy(name, c);
}
Classic::Classic(const Classic & d):Cd(d)
{
    name = new char[strlen(d.name) + 1];
    strcpy(name,d.name);
}
Classic::Classic():Cd()
{
    name = new char[1];
    name = nullptr;
}
Classic::~Classic()
{
    delete[] name;
}
void Classic::Report() const
{
    Cd::Report();
    cout << "name:" << name << endl;
}
Classic & Classic::operator=(const Classic & d)
{
    if (this == &d)
        return *this;
    delete[] name;
    Cd::operator=(d);
    name = new char[strlen(d.name) + 1];
    strcpy(name, d.name);
    return *this;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值