1 #include <iostream>
2 #include <string>
3
4 class A
5 {
6 public:
7 A( const std::string &str )
8 {
9 m_szS = str;
10 }
11
12 A( const A &rhs )
13 {
14 m_szS = rhs.m_szS;
15 }
16
17 A& operator= ( const A &rhs )
18 {
19 if ( this == &rhs )
20 {
21 return *this;
22 }
23
24 m_szS = rhs.m_szS;
25 return *this;
26 }
27
28 std::string m_szS;
29 };
30
31 int main()
32 {
33 //!< 帶參數(shù)基本構(gòu)造,非explicit
34 A a1("SB");
35
36 //!< 不能通過基本構(gòu)造完成,實(shí)質(zhì)上調(diào)用的是對(duì)a1的拷貝構(gòu)造
37 A a2 = a1;
38
39 //!< 驗(yàn)證賦值操作符
40 A a3("SC");
41 a3 = a1; // here
42
43 return 0;
44 }
45
總結(jié):
1.實(shí)例化一個(gè)對(duì)象的時(shí)候,如果用另一個(gè)已有對(duì)象對(duì)其進(jìn)行賦值,實(shí)質(zhì)上調(diào)用的是拷貝構(gòu)造函數(shù),如上述的a2。
2.對(duì)一個(gè)已實(shí)例化對(duì)象采用賦值操作符對(duì)其進(jìn)行賦值,調(diào)用的是賦值操作符重載的函數(shù),如a3。
寫得有點(diǎn)倉促,如有不同意見,歡迎拍板!