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

转: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 plain copy
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值