读书人

一段很简单的程序,但是老出有关问题,在

发布时间: 2012-02-09 18:22:27 作者: rapoo

一段很简单的程序,但是老出问题,在delete的时候就出问题了.大家看看.
头文件:

#include <iostream.h>
#include <string.h>


class bePlus
{
public:
bePlus();
bePlus(int itmp, char *chtmp);
~bePlus();
bePlus operator +(bePlus tmp);
void show();
private:
int m_Value;
char *m_Name;
};

主体代码:


#include "plus.h "


bePlus::bePlus()
{
m_Value = 5;
if ((m_Name = new char(15)) == NULL)
{
cout < < "Not enough memory! " < < endl;
}
else
{
strncpy(m_Name, "default ",15);
m_Name[15]= '\0 ';
}

}

bePlus::bePlus(int itmp, char *chtmp)
{
m_Value= itmp;

if ((m_Name= new char(15)) == NULL)
{
cout < < "Not enough memory! " < < endl;
}
else
{
strncpy(m_Name, "default ",15);
m_Name[15]= '\0 ';
}

if(chtmp != NULL)
{
strncpy(m_Name,chtmp,15);
m_Name[15]= '\0 ';
}

else
{
strncpy(m_Name, "default ",15);
m_Name[15]= '\0 ';
}

}


bePlus::~bePlus()
{

this-> m_Name=NULL;
cout < < "delete a obj " < < endl;
}

bePlus bePlus::operator + (bePlus tmp)
{
char *str;
this-> m_Value += tmp.m_Value;
if((str=new char(strlen(this-> m_Name)+strlen(tmp.m_Name)+1)) == NULL)
{
cout < < "Not enough memory! " < < endl;
}
else
{
strncpy(str,this-> m_Name,strlen(this-> m_Name));
strncat(str,tmp.m_Name,strlen(tmp.m_Name));
str[strlen(this-> m_Name)+strlen(tmp.m_Name)+1]= '\0 ';
}



if((this-> m_Name=new char(strlen(str)+1)) == NULL)
{
cout < < "Not enough memory! " < < endl;
}
else
{
strncpy(this-> m_Name,str,strlen(str));
this-> m_Name[strlen(str)+1]= '\0 ';
}

//delete []str; //此行出错了
str=NULL;
return bePlus(this-> m_Value,this-> m_Name);
}


void bePlus::show()
{
cout < < this-> m_Value < < endl;

cout < < this-> m_Name < < endl;
}


int main(int argc, char *argv[])
{
bePlus a;
bePlus b(3, "wang ");
a.show();
b.show();
bePlus c;
c=a+b;
c.show();

return 0;
}


就是我注释的那一行,出问题,如果注释了,就OK,添加就出错.请高手指教






[解决办法]
bePlus bePlus::operator + (bePlus tmp)又传拷贝,导致内存重复delete。
[解决办法]
bePlus::bePlus()
{
...
if ((m_Name = new char[15]) == NULL) //------------
...
}

bePlus::bePlus(int itmp, char *chtmp)
{
...
if ((m_Name= new char[15]) == NULL) //------------
...
}

bePlus bePlus::operator + (bePlus tmp)
{
...
if((str=new char[strlen(this-> m_Name)+strlen(tmp.m_Name)+1]) == NULL)
...
if((this-> m_Name=new char[strlen(str)+1]) == NULL)
...
delete []str; //此行出错了
...
}
注意:new char(n)与new char[n]是两回事,别搞混了。

读书人网 >C++

热点推荐