C++ 重载=号操作符
#include <iostream>#include <string.h>
using namespace std;
class MyString
{
public:
MyString()
{
m_len = 0;
m_p = new char ;
strcpy (m_p," ");
}
MyString(const char *p)
{
if (p == NULL)
{
m_len = 0;
m_p = new char ;
strcpy (m_p," ");
}
else
{
m_len = strlen (p);
m_p = new char ;
strcpy (m_p,p);
}
}
MyString& operator= (const MyString& obj)
{
if (m_p != NULL)
{
delete [] m_p; //执行到这里,调试停止
m_len = 0;
}
m_len = obj.m_len;
m_p = new char ;
strcpy (m_p,obj.m_p);
}
~MyString()
{
if (m_p != NULL)
{
delete [] m_p;
m_p = NULL;
m_len = 0;
}
}
void printMyString()
{
cout<<m_p<<endl;
}
private:
int m_len;
char *m_p;
};
int main()
{
MyString s1;
MyString s2("abcd");
s1 = s2;
s1.printMyString();
return 0;
}
//执行s1 = s2这一行,进行调试。
//调试到 delete [] m_p;为什么调试会停止? MyString& operator= (const MyString& obj)
{
if (m_p != NULL)
{
delete [] m_p; //执行到这里,调试停止
m_len = 0;
}
m_len = obj.m_len;
m_p = new char ;
strcpy (m_p,obj.m_p);
}
缺少一句返回值语句,在最后应该添加return *this
页:
[1]