什么時(shí)候調(diào)用拷貝構(gòu)造函數(shù)?什么時(shí)候調(diào)用賦值運(yùn)算符?
很多初學(xué)者容易搞不清楚。我來總結(jié)一下就是:
當(dāng)進(jìn)行一個(gè)類的實(shí)例初始化的時(shí)候,也就是構(gòu)造的時(shí)候,調(diào)用的是構(gòu)造函數(shù)(如是用其他實(shí)例來初始化,則調(diào)用拷貝構(gòu)造函數(shù)),非初始化的時(shí)候?qū)@個(gè)實(shí)例進(jìn)行賦值調(diào)用的是賦值運(yùn)算符。
示例如下:
1 #include <iostream>
2 using namespace std;
3 /************************************************************************/
4 /* 該例子用來說明copy constructor 和 賦值運(yùn)算符的調(diào)用情況 */
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;
49
50 cout << "*********b = a************" << endl;
51 b = a;
52 cout << "*********c = 5************" << endl;
53 c = 5;
54
55 return 0;
56 }
57
例子中執(zhí)行結(jié)果是:
*********CTest a****************
CTest()
*********CTest b(a)*************
CTest(const CTest& t)
*********CTest c = a ***********
CTest(const CTest& t)
*********CTest d = 5************
CTest(const int& t)
*********b = a******************CTest& operator=(const CTest& t)
*********c = 5******************CTest& operator=(const int& t)