拷贝构造器(深拷贝与浅拷贝)
一. 概述
复习巩固学习过的知识C++拷贝构造器。
环境:Centos7 64位,g++ 4.8.5
二. 代码与验证
1. 构造与拷贝构造
拷贝构造器(copy constructor)的地位与构造器(constructor)的地位是一样的,都是由无到有的创建过程。拷贝构造器,是由同类对象创建新对象的过程。
通过下面的代码验证几种情况。类A中自实现了构造器,拷贝构造器,析构器。
第28行、第32行代码调用 了构造函数,第29行代码调用了拷贝构造函数,这3行代码比较好理解。
第30行,调用了拷贝构造函数,一时有点不好理解,感觉有点像是调用了赋值运算符函数。但是通过运行结果,可以看到它确实是调用了拷贝构造函数。
可以再回顾一下上面的这句话“由同类对象创建新对象”,可能会更好地帮助理解。
1 #include <iostream>
2
3 using namespace std;
4
5 class A
6 {
7 public:
8 A()
9 {
10 cout<<"constructor A()"<<endl;
11 }
12
13 A(const A &another)
14 {
15 cout<<"A(const A &another)"<<endl;
16 }
17
18 ~A()
19 {
20 cout<<"~A()"<<endl;
21 }
22 protected:
23 int m_a;
24 };
25
26 int main()
27 {
28 A a1; // constructor 构造
29 A a2(a1); // copy constructor 拷贝构造
30 A a3 = a1; // copy constructor 拷贝构造
31
32 A a4; // constructor 构造
33 a4 = a1; // assign
34
35 return 0;
36 }


