一说 拷贝构造函数 && 拷贝赋值函数

谁借莪1个温暖的怀抱¢ 2022-09-01 00:56 287阅读 0赞

特别说明:
拷贝构造函数和拷贝赋值函数要成对出现
移动构造函数和移动赋值函数也要成对出现

拷贝构造函数是在对象被创建时调用的,而赋值函数只能在已经存在了的对象调用。看下面代码:

  1. String a("hello");
  2. String b("world");
  3. String c = a;//这里c对象被创建调用的是拷贝构造函数
  4. //一般是写成 c(a);这里是与后面比较
  5. c = b;//前面c对象已经创建,所以这里是赋值函数

上面说明出现“=”的地方未必调用的都是赋值函数(算术符重载函数),也有可能拷贝构造函数,那么什么时候是调用拷贝构造函数,什么时候是调用赋值函数你?判断的标准其实很简单:如果临时变量是第一次出现,那么调用的只能是拷贝构造函数,反之如果变量已经存在,那么调用的就是赋值函数。

示例代码:
string.h

  1. #ifndef __MYSTRING__
  2. #define __MYSTRING__
  3. #include <string.h>
  4. class String {
  5. public:
  6. String(const char* cstr = 0); // 构造函数
  7. String(const String& str); // 拷贝构造函数 ==》 String s2(s1)
  8. String& operator = (const String& str); // 拷贝赋值函数 ==》 String s2 = s1
  9. ~String();
  10. char* get_c_str() const { return m_data;}
  11. private:
  12. char* m_data;
  13. };
  14. inline String::String(const char* cstr)
  15. {
  16. if (cstr) {
  17. m_data = new char[strlen(cstr) + 1];
  18. strcpy(m_data, cstr);
  19. } else {
  20. m_data = new char[1];
  21. *m_data = '\0';
  22. }
  23. }
  24. inline String::String(const String& str)
  25. {
  26. m_data = new char[strlen(str.m_data) + 1];
  27. strcpy(m_data, str.m_data);
  28. }
  29. inline String& String::operator = (const String& str)
  30. {
  31. if (this == &str) { // 检测自我赋值
  32. return *this;
  33. }
  34. delete[] m_data;
  35. m_data = new char[strlen(str.m_data) + 1];
  36. strcpy(m_data, str.m_data);
  37. return *this;
  38. }
  39. inline String::~String()
  40. {
  41. delete[] m_data;
  42. }
  43. #endif

string.cpp

  1. #include "string.h"
  2. #include <iostream>
  3. using namespace std;
  4. ostream& operator << (ostream& os, const String& str)
  5. {
  6. os << str.get_c_str();
  7. return os;
  8. }
  9. int main()
  10. {
  11. String s1;
  12. String s2("hello");
  13. String s3(s1);
  14. cout << s3 << endl;
  15. s3 = s2;
  16. cout << s3 << endl;
  17. }

output

  1. PS C:\Users\localuser> cd "c:\Users\localuser\Desktop\" ; if ($?) { g++ string.cpp -o string} ; if ($?) { .\string}
  2. hello

发表评论

表情:
评论列表 (有 0 条评论,287人围观)

还没有评论,来说两句吧...

相关阅读

    相关 拷贝构造函数

    特点 也是一种构造函数,其函数名和类名相同,没有返回值类型 只有一个参数,且是同类对象的引用 每个类都必须有一个拷贝构造函数,系统会提供默认构造函数,程

    相关 拷贝构造函数

    一.定义: 就类对象而言,相同类型的类对象是通过拷贝构造函数来完成整个复制过程的。 自定义拷贝构造函数: 1. //拷贝构造函数 2. C