关于拷贝构造函数和赋值运算符

  什么时候调用拷贝构造函数?什么时候调用赋值运算符?

    很多初学者容易搞不清楚。我来总结一下就是:

    当进行一个类的实例初始化的时候,也就是构造的时候,调用的是构造函数(如是用其他实例来初始化,则调用拷贝构造函数),非初始化的时候对这个实例进行赋值调用的是赋值运算符。

    示例如下:

 1  #include  < iostream >
 2  using   namespace  std;
 3  /* ********************************************************************** */
 4  /*  该例子用来说明copy constructor 和 赋值运算符的调用情况                       */
 5  /* ********************************************************************** */
 6  class  CTest
 7  {
 8  public :
 9       int  m_muber;
10      CTest():m_muber( 0 )
11      {
12          cout  <<   " CTest() "   <<  endl;
13      }
14      CTest( const  CTest &  t)
15      {
16          cout  <<   " CTest(const CTest& t) "   <<  endl;
17           this -> m_muber  =  t.m_muber;
18      }
19      CTest( const   int &  t)
20      {
21          cout  <<   " CTest(const int& t) "   <<  endl;
22           this -> m_muber  =  t;
23      }
24      CTest &   operator = ( const  CTest &  t)
25      {
26          cout  <<   " CTest& operator=(const CTest& t) "   <<  endl;
27           this -> m_muber  =  t.m_muber;
28           return   * this ;
29      }
30      CTest &   operator = ( const   int &  t)
31      {
32          cout  <<   " CTest& operator=(const int& t) "   <<  endl;
33           this -> m_muber  =  t;
34           return   * this ;
35      }
36 
37 
38  };
39  int  main()
40  {  

41      cout  <<   " *********CTest a**************** "   <<  endl;
42      CTest a;  // 调用默认构造函数 
43      cout  <<   " *********CTest b(a)************* "   <<  endl;
44      CTest b(a);  // 调用拷贝构造函数 
45      cout  <<   " *********CTest c = a *********** "   <<  endl;
46      CTest c  =  a;  // 调用拷贝构造函数 
47      cout  <<   " *********CTest d = 5************ "   <<  endl;
48      CTest d  =   5 ; // 调用拷贝构造函数,参数为int 型,会进行类型转换:
49 
50      cout  <<   " *********b = a************ "   <<  endl;
51      b  =  a; // 调用重载操纵符=
52      cout  <<   " *********c = 5************ "   <<  endl;
53      c  =   5 ;   // 调用重载操纵符=,参数为int 型,会进行类型转换:
54 
55       return   0 ;
56  }
57 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值