C++拷贝构造函数剖析(copy constructor)

首先让我们看一下,下面的代码,然后再做剖析:

  1 #include <iostream>                                                                                                                                                         
  2 #include <string>
  3 using namespace std;
  4 class person{
  5 public:
  6     person()
  7     {
  8         cout << "this is default constructor!" << endl;
  9     }
 10     person(string temp)
 11     {
 12         name = temp;
 13         cout << "this is parameter constructor!" << endl;
 14     }
 15     person(const person& temp)
 16     {
 17         this->name = temp.name;
 18         cout << "this is copy constructor!" << endl;
 19     }
 20     person& operator = (person& temp)
 21     {
 22         this->name = temp.name;
 23         cout << "this is = function " << endl;
 24         return *this;
 25     }
 26 
 27     string name;
 28 };
 29 int main()
 30 
 31     person a;
 32     person b;
 33     a = b;
 34     person c = a;
 35     person d("who");
 36 
 37     return 0;
 38 
 39 }

运行输出的结果:

  C++拷贝构造函数剖析(copy constructor)

 

因此我们可以看出:

当我们使用已经初始化过后的对象a,b,让 a = b,实质上调用的是运算符重载。

当我们使用 person c = a;的时候,实质上调用的是copy construcotr(拷贝构造函数),也就是说这句话相当于 person c(a);

person c(a) 相当于 person c.person(a);即调用copy constructor

当a的值传递给copy constructor (person(const person& temp))的时候,如果没有加引用,即(person(person temp)),

那就相当于 再次构造,即perosn temp = a,所以我们需要再次的调用copy constructor,所以就陷入了无限的递归之中。

 用图表示为(将就着看一下吧):

  C++拷贝构造函数剖析(copy constructor) 

而至于const的原因:

  其一:在函数体内能够不改变传递进来的数值。

  其二:如果我们传递的是person a("zhangfei"),同时没有 person(string temp) 的存在,这时通过copy constructor也是可以赋值的。

 

原文链接: https://www.cnblogs.com/jianmoxiansheng-Guo/p/12892967.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++拷贝构造函数剖析(copy constructor)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/348651

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午5:10
下一篇 2023年3月2日 上午5:10

相关推荐