bubbleTg 2017-05-09 15:30 采纳率: 75%
浏览 915

c++中的动态内存释放问题

 #include<iostream>
#include<cstring>
using namespace std;

class CGoods
{
public:
    long no;
    char *p_name;
    double price;
public:
    CGoods() {}
    CGoods(long no1, char *p_name1, double price1);
    CGoods(const CGoods &C)         //深度拷贝构造函数
    {
        no = C.no;
        int n = strlen(C.p_name);
        p_name = new char[n + 1];
        strcpy(p_name, C.p_name);
        price = C.price;
    }
    void show();

    virtual ~CGoods()
    {
        cout << "nkhao啊" << p_name << endl;
        delete []p_name;
    }
};
CGoods::CGoods(long no1, char *p_name1, double price1)
{
    no = no1;
    int n = strlen(p_name1);
    p_name = new char[n + 1];
    strcpy(p_name, p_name1);
    price = price1;
}
void CGoods::show()
{
    cout << p_name << " ";
}
class CClothes :public CGoods
{
public:
    char *p_brand;
    CGoods Cc;
    CClothes(long no1, char *p_name1, double price1, char *p_brand1) :Cc(no1, p_name1, price1)
    {
        CGoods Cc1=Cc;
        int n = strlen(p_name1);
        p_brand = new char[n + 1];
        strcpy(p_brand, p_brand1);
    }
    void usedFor()
    {
        Cc.show();
        cout << p_brand << endl;
    }
    ~CClothes()
    {
        delete[]p_brand;
    }
};
class CFood :public CGoods
{
public:
    char *p_brand;
    CGoods Cc;
    //CGoods Cc1;
    CFood(long no1, char *p_name1, double price1, char *p_brand1) :Cc(no1, p_name1, price1)
    {
        CGoods Cc1 = Cc;
        //Cc1 = Cc;
        int n = strlen(p_name1);
        p_brand = new char[n + 1];
        strcpy(p_brand, p_brand1);
    }
    void usedFor()
    {
        Cc.show();
        cout << p_brand << endl;
    }
    ~CFood()
    {
        delete[]p_brand;
    }

};
int main()
{
    long no;
    char *p= new char[1];
    double price;
    char *p1 = new char[1];
    cin >> no >> p >> price >> p1;
    CClothes ccl(no, p, price, p1);
    ccl.usedFor();
    cin >> no >> p >> price >> p1;
    CFood cfood(no, p, price, p1);
    cfood.usedFor();
    /*delete[]p;
    delete[]p1;*/
    return 0;
}

图片说明

为什么在释放内存的时候,最后一次发生了冲突??
(我在析构函数中加cout << "nkhao啊" << p_name << endl;是方便结果分析)

  • 写回答

2条回答 默认 最新

  • devmiao 2017-05-09 16:16
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题