本文共 1121 字,大约阅读时间需要 3 分钟。
String类中系统默认实现了4个函数,但是在程序中我们常常自己要去实现,下面就是实现的代码:
在使用String的过程中,如果拷贝构造函数和赋值函数采用了系统设计的话,会出现错误,因为系统只是实现了浅拷贝,也就是只用了指针赋值的形式,这样往往在程序设计的过程中出现错误。所以如果自己用到了,一定要自己实现:
- class String
- {
- public:
- String();
- String(const String &other);
- String(const char *str = NULL);
- String& operator=(const String &other);
- ~String();
- private:
- char *m_data;
- };
-
- String::String()
- {
- m_data = (char*)malloc(sizeof(char)*1);
- *m_data = '\0';
- }
-
- String::String(const String &other)
- {
- int length = strlen(other.m_data);
- m_data = new char[length+1];
- strcpy(m_data, other.m_data);
- }
-
- String::String(const char *str)
- {
- if (NULL == str)
- {
- m_data = new char[1];
- *m_data = '\0';
- }
- else
- {
- int length = strlen(str);
- m_data = new char[length+1];
- strcpy(m_data, str);
- }
- }
-
- String& String::operator=(const String &other)
- {
- if (this == &other)
- {
- return *this;
- }
- delete []m_data;
- int length = strlen(other.m_data);
- m_data = new char[length+1];
- strcpy(m_data, other.m_data);
- return *this;
- }
-
- String::~String()
- {
- delete []m_data;
- }
转载地址:http://xcrgi.baihongyu.com/