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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试