【c++常见问题】-写一个string实现

本文详细介绍了C++中自定义String类的实现方法,包括构造函数、析构函数、拷贝构造函数及赋值操作符重载等关键部分,并提供了具体的代码实现。

  一个string类的实现必须很快速写出来。

 1 class String
 2 {
 3     public:
 4     String(const char *str = NULL);// 普通构造函数
 5     String(const String &other); //拷贝构造函数
 6     ~ String(void); //析构函数
 7     String & operator =(const String &other);//赋值函数
 8     private:
 9     char *m_data;// 用于保存字符串
10 };
11 
12 //普通构造函数
13 String::String(const char *str)
14 {
15     if(str==NULL)
16     {
17         m_data = new char[1]; // 对空字符串自动申请存放结束标志'\0'的//加分点:对m_data加NULL 判断
18         *m_data = '\0';
19     }else{
20         int length = strlen(str);
21         m_data = new char[length+1]; // 若能加 NULL 判断则更好
22         strcpy(m_data, str);
23     }
24 }
25 
26 // String的析构函数
27 String::~String(void)
28 {
29     delete[] m_data; // 或delete m_data;
30 }
31 
32 //拷贝构造函数
33 String::String(const String &other) // 输入参数为const型
34 {
35     int length = strlen(other.m_data);
36     m_data = new char[length+1]; //对m_data加NULL 判断
37     strcpy(m_data, other.m_data);
38 }
39 
40 String & String::operator =(const String &other) // 输入参数为const
41 42 {
43     if(this != &other) //检查自赋值
44 {
45     String strTemp(str);
46     char* pTemp = strTemp.m_pData;
47     strTemp.m_pData = m_pData;
48     m_pData = pTemp;
49 }
50     return *this; //返回本对象的引用
51 }
View Code
 1 //赋值函数, 欠佳做法
 2 String & String::operator =(const String &other) // 输入参数为const
 3  4 {
 5     if(this == &other) //检查自赋值
 6     return *this;
 7     delete[] m_data; //释放原有的内存资源
 8     int length = strlen( other.m_data );
 9     m_data = new char[length+1]; //对m_data加NULL 判断
10     strcpy( m_data, other.m_data );
11     return *this; //返回本对象的引用
12 }
View Code

 

转载于:https://www.cnblogs.com/liqilihaha/p/4025698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值