首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于CString的类解决办法

2012-02-28 
关于CString的类这两天看了高质量c++编程,我把里面关于Cstring的实现自己在VC6.0中试了一下://myString.h#

关于CString的类
这两天看了高质量c++编程,我把里面关于Cstring的实现自己在VC6.0中试了一下:

//myString.h
#include   "stdafx.h "
class   myString
{
public:
myString(const   char   *   str=NULL);
myString(const   myString   &other);
~myString(void);
myString   &   operator   =(const   myString   &other);
private:
char   *m_data;
};


//mystring.cpp
#include   "stdafx.h "
#include   "string.h "
#include   "mycstring.h "

myString::myString(const   char   *   str)
{
if   (str   ==   NULL)
{
m_data   =   new   char(1);
*m_data   =   '\0 ';
}
else
{
int   len   =   strlen(str);
m_data   =   new   char(len+1);
strcpy(m_data,str);
}
}
myString::myString(const   myString   &other)
{

int   len   =   strlen(other.m_data);
m_data   =   new   char(len+1);
strcpy(m_data,other.m_data);
}
myString::~myString(void)
{
delete     m_data;
//m_data   =   0;
}

myString   &   myString::operator   =(const   myString   &other)
{
if   (this   ==   &other)   {
return   *this;
}

delete   []   m_data;

m_data   =     new   char(strlen(other.m_data)+1);

strcpy(m_data,other.m_data);

return   *this;

}


//   main   函数

#include   "stdafx.h "
#include   "mycstring.h "

int   main(int   argc,   char*   argv[])
{

myString   *mystr1=   new   myString( "dddddddd ");

delete   mystr1;//出错

return   0;
}


出错的提示信息为:
DAMAGE:   after   Normal   block(#54)   at   0x00431860

我在内存中看了0x00431860   这个地址   就是   mystr1   的   m_data   指向的位置.里面存放的就是字符串 "dddddddd "



[解决办法]
myString::myString(const char * str)
{
if (str == NULL)
{
m_data = new char(1); //应为 m_data = new char[1];
*m_data = '\0 ';
}
else
{
int len = strlen(str);
m_data = new char(len+1); ////应为 m_data = new char[len+1];
strcpy(m_data,str);
}
}
myString::myString(const myString &other)
{

int len = strlen(other.m_data);
m_data = new char(len+1); //应为 m_data = new char[len+1];
strcpy(m_data,other.m_data);
}
......................
myString & myString::operator =(const myString &other)
{
...................
m_data = new char(strlen(other.m_data)+1);
//应为 m_data = new char[strlen(other.m_data)+1];

strcpy(m_data,other.m_data);

return *this;

}


[解决办法]
m_data = new char(len+1) <==> new char[1];*m_data=len+1;

new char[n]就是想要的效果:new n个char
[解决办法]
new char(n); 是申请一个char内存,置它的值为n
new char[n]; 是申请n个char内存
------解决方案--------------------


这种错误不可能在编译时候给出提示 ...
[解决办法]
1.申请新资源时用new char[n];
2.析构函数时delete [] m_data;
[解决办法]
new char() 申请一个char型值为 ' '的字符
new char[] 是申请一个char的动态数组

热点排行