类中拷贝构造函数和赋值构造函数的区别
假如存在以下代码:
class Test
{};
int main()
{
Test A;
Test B(A); //调用拷贝构造函数
Test C = A; //调用拷贝构造函数
B = A; //此处才调用赋值构造函数
}
以下给出测试代码:
1 #include <iostream> 2 #include <stdlib.h> 3 using namespace std; 4 5 class AAA 6 { 7 public: 8 AAA() 9 { 10 value++;cout << "value is " << value << endl; 11 } 12 ~AAA() 13 { 14 value++;cout << "delete value is " << value << endl; 15 } 16 17 AAA(AAA& tmp) 18 { 19 value++;cout << "copy value is " << value << endl; 20 } 21 const AAA& operator=(const AAA& tmp) 22 { 23 value++;cout << "operator value is " << value << endl; 24 } 25 26 private: 27 static int value; 28 }; 29 int AAA::value = 0; //注意类中的静态变量必须在类外初始化 30 31 int test(AAA a) 32 { 33 cout << "test start" << endl; 34 AAA test = a; 35 36 //return 0; //即便注释掉,也是默认为return的,即会清理局部变量 37 } 38 int main() 39 { 40 AAA A; 41 AAA B(A); 42 AAA C = A; 43 B = A; 44 45 cout << "*****************************" << endl; 46 test(A); 47 cout << "*****************************" << endl; 48 exit(0); //注意此处和用return 0的区别,即不会调用析构函数 49 }