本文共 2284 字,大约阅读时间需要 7 分钟。
//实现string类,构造函数,析构函数、拷贝构造函数、赋值运算符、重载 + 、 ==#include "my_string.h"#includeusing namespace std;MyString::MyString()//默认构造函数 //:s(new char(1)) //, length(1) :s(NULL) , length(0){ }MyString::MyString(const char* str)//构造函数{ if (str == NULL) { return; } length = strlen(str); s = new char[length + 1]; memset(s, 0, length + 1); strcpy(s, str);}MyString::MyString(const MyString& str1)//拷贝构造函数 :s(NULL) , length(0){ if (0 == str1.length) { return; } length = strlen(str1.s); s = new char[length + 1]; strcpy(s, str1.s);}MyString::~MyString(){ if (NULL != s) { delete[] s; s = NULL; }}MyString& MyString::operator=(const MyString& str1){ if (0 == strlen(str1.s)) { exit(-1); } int len_str1 = std::strlen(str1.s); if (this == &str1) { return *this; } if (length < len_str1) { delete[] s; s = NULL; length = len_str1 + 1; s = new char[length]; memset(s, 0, length); strcpy(s, str1.s); } else { memset(s, 0, length); strcpy(s, str1.s); } return *this;}MyString operator + (const MyString& str1, const MyString& str2){ if ((NULL == &str1) && (NULL == &str2)) { return NULL; } MyString total;//默认构造函数 int len_str1 = std::strlen(str1.s); int len_str2 = std::strlen(str2.s); total.s = new char[len_str1 + len_str2 + 2]; memset(total.s, 0, len_str1 + len_str2 + 2); strcpy(total.s, str1.s); strcat(total.s, str2.s); return total;//拷贝构造,默认构造,拷贝构造(重新拷贝一个中间的对象),析构函数(释放total)}bool operator==(const MyString& str1, const MyString& str2){ int ret = strcmp(str1.s, str2.s); if (0 == ret) { return true; } else { return false; }}int main(){ MyString str1;//默认构造函数 MyString str2("abc");//构造函数,默认构造函数 MyString str3(str2);//拷贝构造函数,默认构造函数 str1 = str2;//赋值 MyString str4("hello");//构造函数,默认构造函数 MyString str5("word");//构造函数,默认构造函数 MyString total = str4 + str5;//重载加 bool Isequal(str1 == str4);//重载 return 0;//6次析构}
#ifndef _MY_STRING_H_#define _MY_STRING_H_#include#include #include class MyString{private: char* s = NULL; int length; public: MyString();//默认构造函数 MyString(const char* str);//构造函数,赋给成员的值 MyString(const MyString& str1);//拷贝构造函数 ~MyString();//析构函数 MyString& operator=(const MyString& str1); friend MyString operator+(const MyString& str1, const MyString& str2); friend bool operator==(const MyString& str1, const MyString& str2);};#endif
转载地址:http://ulypi.baihongyu.com/