编写类String 的构造函数、析构函数和赋值函数,已知类String 的原型为:
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operate =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
- #include <iostream>
- class String
- {
- public:
- String(const char *str=NULL);
- String(const String &str);
- String & operator =(const String &str);
- ~String();
- protected:
- private:
- char* m_data;
- };
-
-
- String::String(const char *str){
- if (str==NULL){
- m_data=new char[1];
- if (m_data==NULL){
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- m_data[0]='\0';
- }
- else{
- int length=strlen(str);
- m_data=new char[length+1];
- if (m_data==NULL){
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- strcpy(m_data,str);
- }
- }
-
- String::String(const String &str){
- int length=strlen(str.m_data);
- m_data=new char[length+1];
- if (m_data==NULL){
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- strcpy(m_data,str.m_data);
- }
-
- String& String::operator =(const String &str){
- if (this==&str)
- return *this;
- int length=strlen(str.m_data);
- delete [] m_data;
- m_data= new char[length+1];
- if (m_data==NULL){
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- strcpy(m_data,str.m_data);
- return *this;
- }
-
- String::~String(){
- delete [] m_data;
- }
-
- void main(){
- String a;
- String b("abc");
- system("pause");
- }