C++随笔:为什么没有调用赋值运算符?

代码如下,按理应该调用复制运算符啊,为何却是调用了复制构造函数:

 1 #include <iostream>
 2 using std::cout;
 3 using std::endl;
 4 using std::string;
 5 
 6 class Test
 7 {
 8 public:
 9     Test()
10     {   
11         cout << "The default constructor is called!" << endl;
12     }   
13 
14     Test(const Test &rhs)
15     :strTest(rhs.strTest)
16     {   
17         cout << "Test copying function is called!" << endl;
18     }   
19 
20     Test & operator=(const Test &rhs)
21     {
22         strTest = rhs.strTest;
23         cout << "Test copy assignment function is called!" << endl;
24         return *this;
25     }
26 
27 private:
28     string strTest;
29 };
30 
31 int main()
32 {
33     Test myTestA;
34     Test myTestB = myTestA;
35 
36     return 0;
37 }

编译后的运行结果为:

1 [tortoise@sea temp]$ ./test
2 The default constructor is called!
3 Test copying function is called!
4 [tortoise@sea temp]$

 

嗯,想明白了:

Test myTestB = myTestA;

Test myTestB(myTestA);

是相同的,都是做初始化操作,下面这样才会调用赋值运算符:

Test myTestB;
myTestB = myTestA;

 

转载于:https://www.cnblogs.com/StupidTortoise/p/3655527.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值