#include <string.h>
#include <stdio.h>
class user_string
{
public :
user_string();
user_string(const char *src);
user_string(const user_string &other);
user_string &operator = (const user_string &other);
~user_string();
void show();
private:
char *m_pdata;
};
user_string::user_string()
{
}
user_string::user_string(const user_string &other)
{
}
user_string::user_string(const char*src)
{
if ( src == NULL )
{
m_pdata = new char[1];
m_pdata[0] = '\0';
}
else
m_pdata = new char [strlen(src) + 1];
strcpy(m_pdata, src);
}
user_string::~user_string()
{
delete []m_pdata;
}
user_string & user_string::operator = (const user_string &other)
{
if ( this == &other )
return *this;
delete []m_pdata;
m_pdata = new char[strlen(other.m_pdata) + 1];
strcpy(m_pdata, other.m_pdata);
return * this;
}
void user_string::show()
{
printf("%s", m_pdata);
}
void main()
{
user_string a("123");
user_string b("456");
b = b;
b = a;
//b = a;
}
本文介绍了一个简单的自定义字符串类的实现过程,包括构造函数、拷贝构造函数、赋值运算符重载及析构函数等核心成员函数的定义。通过这个类可以更好地理解C++中字符串对象的内存管理和深拷贝机制。
2777

被折叠的 条评论
为什么被折叠?



