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ù)基本構造,非explicit
34 A a1("SB");
35
36 //!< 不能通過基本構造完成,實質(zhì)上調(diào)用的是對a1的拷貝構造
37 A a2 = a1;
38
39 //!< 驗證賦值操作符
40 A a3("SC");
41 a3 = a1; // here
42
43 return 0;
44 }
45
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ù)基本構造,非explicit
34 A a1("SB");
35
36 //!< 不能通過基本構造完成,實質(zhì)上調(diào)用的是對a1的拷貝構造
37 A a2 = a1;
38
39 //!< 驗證賦值操作符
40 A a3("SC");
41 a3 = a1; // here
42
43 return 0;
44 }
45
總結:
1.實例化一個對象的時候,如果用另一個已有對象對其進行賦值,實質(zhì)上調(diào)用的是拷貝構造函數(shù),如上述的a2。
2.對一個已實例化對象采用賦值操作符對其進行賦值,調(diào)用的是賦值操作符重載的函數(shù),如a3。
寫得有點倉促,如有不同意見,歡迎拍板!
沒有呢