回 帖 发 新 帖 刷新版面

主题:析构函数问题

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class process
{
   public:

       string pname;
       int has;
       int need;

       process()
       {
           this->pname="";
           this->has=0;
           this->need=0;
       }

       ~process(){}
};

class banker
{
   private:

       int number;
       process*p;

   public:

       banker()
       {
           this->number=0;
           this->p=NULL;
       }

       //~banker(){delete p;}

       void ini();
       void judge();
};

int _tmain(int argc, _TCHAR* argv[])
{
    banker b;
    b.ini();
    b.judge();

    system("pause");
    return 0;
}


void banker::ini()
{
    cout<<"请输入进程的数量: ";
    cin>>number;
    p=new process[number];

    for(int i=0;i<number;i++)
    {
        cout<<endl;
        cout<<"请输入进程"<<i+1<<"的名字"<<endl;
        cin>>p[i].pname;
        cout<<"请输入进程"<<i+1<<"已有资源数量"<<endl;
        cin>>p[i].has;
        cout<<"请输入进程"<<i+1<<"需要资源数量"<<endl;
        cin>>p[i].need;
    }

    cout<<endl;
    cout<<"***********************"<<endl;
    cout<<"进程"<<" "<<"已有资源"<<" "<<"需要资源"<<endl;
    for(int j=0;j<number;j++)
    {
        cout<<" "<<p[j].pname<<"       "<<p[j].has<<"        "<<p[j].need<<endl;
    }
    cout<<"***********************"<<endl;

}

void banker::judge()
{
    int idle=0,count=0,increase=0;
    int*mark=NULL;

    mark=new int[number];
    for(int k=0;k<number;k++)
    {
        mark[k]=0;
    }

    cout<<endl;
    cout<<"请输入目前空闲资源的数量: ";
    cin>>idle;
    
    while(true)
    {
        increase=0;

        for(int j=0;j<number;j++)
        {
            if(mark[j]!=2)
            {
                if(mark[j]==1)
                    mark[j]=2;

                else if((idle+p[j].has)>=p[j].need )
                {
                    idle+=p[j].has;
                    mark[j]=1;
                    increase++;
                }
            }
        }

        count+=increase;
        if(count==number)
            break;

        else if(increase==0)
        {
            count=0;
            break;
        }
    }
    
    cout<<endl;
    if(count==number)
        cout<<"资源分配状态: 安全"<<endl;

    else 
        cout<<"资源分配状态: 不安全"<<endl;

    delete[] mark;
}


//为什么总是析构函数那里有问题

回复列表 (共3个回复)

沙发

怎么提示呢?
delete[] mark;

mark = NULL;

板凳

按常理来说,一般析构函数出问题,多半是访问越界造成的。楼主可以调试分析一下。

3 楼

//~banker(){delete p;}你是说这儿出错吗?
肯定是错的撒,p=new process[number];
你都会用delete[] mark;不会用delete[] p吗?

我来回复

您尚未登录,请登录后再回复。点此登录或注册