编写类String 的构造函数、析构函数和赋值函数

来源:互联网 发布:js 展开所有树节点 编辑:程序博客网 时间:2024/06/06 07:50

转:http://blog.csdn.net/zhuimengzh/article/details/6708882

编写类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; // 用于保存字符串
};

 

 

[cpp] view plaincopy
  1. #include <iostream>  
  2. class String  
  3. {  
  4. public:  
  5.     String(const char *str=NULL);//普通构造函数  
  6.     String(const String &str);//拷贝构造函数  
  7.     String & operator =(const String &str);//赋值函数  
  8.     ~String();//析构函数  
  9. protected:  
  10. private:  
  11.     char* m_data;//用于保存字符串  
  12. };  
  13.   
  14. //普通构造函数  
  15. String::String(const char *str){  
  16.     if (str==NULL){  
  17.         m_data=new char[1]; //对空字符串自动申请存放结束标志'\0'的空间  
  18.     if (m_data==NULL){//内存是否申请成功  
  19.         std::cout<<"申请内存失败!"<<std::endl;  
  20.         exit(1);  
  21.     }  
  22.     m_data[0]='\0';  
  23.     }  
  24.     else{  
  25.         int length=strlen(str);  
  26.         m_data=new char[length+1];  
  27.         if (m_data==NULL){//内存是否申请成功  
  28.             std::cout<<"申请内存失败!"<<std::endl;  
  29.             exit(1);  
  30.         }  
  31.         strcpy(m_data,str);  
  32.     }  
  33. }  
  34. //拷贝构造函数  
  35. String::String(const String &str){ //输入参数为const型  
  36.     int length=strlen(str.m_data);  
  37.     m_data=new char[length+1];  
  38.     if (m_data==NULL){//内存是否申请成功  
  39.         std::cout<<"申请内存失败!"<<std::endl;  
  40.         exit(1);  
  41.     }  
  42.     strcpy(m_data,str.m_data);  
  43. }  
  44. //赋值函数  
  45. String& String::operator =(const String &str){//输入参数为const型  
  46.     if (this==&str) //检查自赋值  
  47.         return *this;  
  48.     int length=strlen(str.m_data);  
  49.     delete [] m_data;//释放原来的内存资源  
  50.     m_data= new char[length+1];  
  51.     if (m_data==NULL){//内存是否申请成功  
  52.         std::cout<<"申请内存失败!"<<std::endl;  
  53.         exit(1);  
  54.     }  
  55.     strcpy(m_data,str.m_data);  
  56.     return *this;//返回本对象的引用  
  57. }  
  58. //析构函数  
  59. String::~String(){  
  60.     delete [] m_data;  
  61. }  
  62.   
  63. void main(){  
  64.     String a;  
  65.     String b("abc");  
  66.     system("pause");  
  67. }  

 

0 0
原创粉丝点击