strcat 乱码问题
#include<iostream>#include<assert.h>
//#include<string>
using namespace std;
class MyString {
public:
MyString(char *pstr);
MyString(const MyString& str);
~MyString();
void ShowString(); //显示字符串
void Add(const MyString& str); //与另外一个相加
void Copy(const MyString& str); //从另外一个拷贝
int GetLength();
private:
char *m_buf;
};
MyString ::MyString (char *pstr)
{
if(pstr ==NULL)
m_buf =new char('\0');
else{
m_buf =new char[strlen(pstr)+1];
strcpy(m_buf,pstr);
}
}
MyString ::MyString (const MyString& str)
{
assert(str.m_buf !=NULL);
m_buf=new char[strlen(str.m_buf)+1];
strcpy(m_buf ,str.m_buf);
}
MyString::~MyString()
{
delete []m_buf ;
}
void MyString ::ShowString ()
{
cout<<"show string: "<<m_buf<<endl;
}
void MyString::Add(const MyString& str)
{
assert(str.m_buf !=NULL);
int len=strlen(m_buf)+strlen(str.m_buf)+1;
char *p=new char[len];
strcpy(p,m_buf);
strcat(p,str.m_buf);
// delete []m_buf ;
m_buf=new char[len];
strcat(m_buf ,p);
delete []p;
}
void MyString::Copy(const MyString& str)
{
assert(str.m_buf !=NULL);
m_buf=new char[strlen(str.m_buf)+1];
strcpy(m_buf ,str.m_buf );
}
int MyString::GetLength()
{
if(m_buf ==NULL)
return 1;
return strlen(m_buf)+1;
}
void main()
{
MyString mystring("haoyasen"),mystring2("shuaizhenhao");
//mystring(mystring2);
mystring.ShowString();
cout<<"len: "<<mystring .GetLength ()<<endl;
mystring.Add(mystring2);mystring.ShowString ();//不能正确显示
mystring.Copy(mystring2);mystring.ShowString();
}