题目:给定一个String类的类声明,要求实现类的函数体
类声明如下
class String{ public: String(const char *str = NULL); String(const String &another); ~String(void); String& operator=(const String &rhs); char* Get(void)const; private: char *m_data; };
类的实现如下
//实现简单的String类 class String{ public: String(const char *str = NULL); String(const String &another); ~String(void); String& operator=(const String &rhs); char* Get(void)const; private: char *m_data; }; //实现构造函数 String::String(const char *str){ if(str == NULL){ this->m_data = new char[1]; this->m_data[0] = '\0'; } else{ this->m_data = new char[strlen(str)+1]; strcpy(this->m_data, str); } } //实现拷贝构造函数 String::String(const String &another){ this->m_data = new char[strlen(another.m_data)+1]; strcpy(this->m_data, another.m_data); } //实现析构函数 String::~String(void){ delete[] this->m_data; } //实现操作符= String& String::operator=(const String &rhs){ if(this == &rhs){ //如果是相同就不复制 return *this; } delete[] this->m_data; this->m_data = new char[strlen(rhs.m_data)+1]; strcpy(this->m_data, rhs.m_data); return *this; } //实现Get char* String::Get(void)const{ return this->m_data; };
时间: 2024-10-12 22:52:11