析构函数释放出错
#include<iostream>using namespace std;
class CString
{
char * m_pbuff; //指向字符串的指针
int m_length; //表示当前字符串的最大允许长度,也就是字符数组的长度
public:
CString(); //构造函数1,设置为空字符串,m_length=100
CString(char *src); //构造函数2,在考虑了src的长度后初始化当前对象,m_length >= src的长度 + 1
CString(char ch); //构造函数3,0号元素赋值为ch, m_length=100
CString(CString & a);
int SetString(char *src); //设置字符串,在考虑了src的长度后设置当前对象, m_length >= src的长度 + 1
friend ostream& operator<<(ostream& Out, const CString& S); //输出字符串
~CString()
{
delete []m_pbuff;
}
};
CString::CString()
{
m_length = 100;
m_pbuff = new char[m_length];
for (int i = 0; i < m_length; ++i)
m_pbuff[i] = '\0';
}
CString::CString(char *src)
{
m_length = strlen(src) + 1;
m_pbuff = new char[m_length];
int i;
for (i = 0; i < m_length; ++i)
m_pbuff[i] = src[i];
m_pbuff[i] = '\0';
}
CString::CString(char ch)
{
m_length = 100;
m_pbuff = new char[m_length];
m_pbuff[0] = ch;
m_pbuff[1] = '\0';
}
int CString::SetString(char *src)
{
m_length = strlen(src) + 1;
m_pbuff = new char[m_length];
int i;
for (i = 0; i < m_length; ++i)
m_pbuff[i] = src[i];
m_pbuff[i] = '\0';
return 1;
}
ostream& operator<<(ostream& Out, const CString& S)
{
Out << S.m_pbuff << endl;
return Out;
}
CString::CString(CString & a)
{
m_length = a.m_length;
m_pbuff = new char[a.m_length];
int i;
for (i = 0; i < m_length; ++i)
m_pbuff[i] = a.m_pbuff[i];
m_pbuff[i] = a.m_pbuff[i];
}
void main()
{
CString s1;
cout << s1;
s1.SetString("abc1");
cout << s1;
CString s2("abc2");
cout << s2;
CString s3('a');
cout << s3;
CString s4(s2);
cout << s4;
}