c++中string类的实现

首先说明一下:拷贝构造函数和赋值函数还不一样

拷贝构造函数:刚刚开辟好一块内存空间,就是利用传入的对象对这块内存进行初始化(注意深拷贝和浅拷贝的问题)

拷贝构造::一种特殊的构造函数,用基于同一类的一个对象构造和初始化另一个对象。
当没有拷贝构造函数时,通过默认拷贝构造函数来创建一个对象。
A a;
A b(a);
A b= a;
都是拷贝构造函数来创建对象b
b 对象之前是不存在的,用a对象来构造和初始化b的!!!

何时调用拷贝构造函数
1. 对象以值传递的方式传入函数内
2. 对象以值传递的方式从函数返回
3. 对象需要通过另一个对象初始化

赋值函数:已经有一个已经初始化好的对象,说明此时已经调用过普通的构造函数,此时传入另一个对象对它进行赋值,需要先delete释放原来对象的内存空间,然后重新开辟空间使用传进来的对象进行赋值。

赋值函数:: 一个类的对象向该类的另一个对象赋值。

当没有重载赋值函数(赋值运算符)时,通过默认赋值函数来进行赋值操作。
A a;
A b;
b =a ;
a, b 对象是已经存在的,用a对象来赋值给b!!!!!!

赋值运算符的重载声明:
A& operator = (const A& other)

 

转载原文地址:

https://blog.csdn.net/caoshangpa/article/details/51530482

请编写String的上述4个函数。

这个在面试或笔试的时候常问到或考到。

已知类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. };

请编写String的上述4个函数。

 

 
  1. //普通构造函数

  2. String::String(const char *str)

  3. {

  4. if (str == NULL)

  5. {

  6. m_data = new char[1];// 得分点:对空字符串自动申请存放结束标志'\0'的,加分点:对m_data加NULL判断

  7. *m_data = '\0';

  8. }

  9. else

  10. {

  11. int length = strlen(str);

  12. m_data = new char[length + 1];// 若能加 NULL 判断则更好

  13. strcpy(m_data, str);

  14. }

  15. }

  16.  
  17.  
  18. // String的析构函数

  19. String::~String(void)

  20. {

  21. delete[] m_data; // 或delete m_data;

  22. }

  23.  
  24.  
  25. //拷贝构造函数

  26. String::String(const String &other)// 得分点:输入参数为const型

  27. {

  28. int length = strlen(other.m_data);

  29. m_data = new char[length + 1];// 若能加 NULL 判断则更好

  30. strcpy(m_data, other.m_data);

  31. }

  32.  
  33.  
  34. //赋值函数

  35. String & String::operator = (const String &other) // 得分点:输入参数为const型

  36. {

  37. if (this == &other)//得分点:检查自赋值

  38. return *this;

  39. if (m_data)

  40. delete[] m_data;//得分点:释放原有的内存资源

  41. int length = strlen(other.m_data);

  42. m_data = new char[length + 1];//加分点:对m_data加NULL判断

  43. strcpy(m_data, other.m_data);

  44. return *this;//得分点:返回本对象的引用

  45. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值