相关知识:
- 如果类的设计者不写复制构造函数,编译器就会自动生成复制构造函数。
- 大多数情况下,其作用是实现从源对象到目标对象逐个字节的复制,即使得目标对象的每个成员变量都变得和源对象相等。
- 编译器自动生成的复制构造函数称为“默认复制构造函数”。
- 注意,默认构造函数(即无参构造函数)不一定存在,但是复制构造函数总是会存在。
复制构造函数在以下三种情况下会被调用:
- 当用一个对象去初始化同类的另一个对象时,会引发复制构造函数被调用。
- 如果函数 F 的参数是类 A 的对象,那么当 F 被调用时,类 A 的复制构造函数将被调用。换句话说,作为形参的对象,是用复制构造函数初始化的,而且调用复制构造函数时的参数,就是调用函数时所给的实参。
- 如果函数的返冋值是类 A 的对象,则函数返冋时,类 A 的复制构造函数被调用。换言之,作为函数返回值的对象是用复制构造函数初始化的,而调用复制构造函数时的实参,就是 return 语句所返回的对象。
代码涉及的内容:
复制构造函数的适用情况
对象的定义形式 复制初始化
形参与返回值
初始化容器元素
构造函数与数组元素
赋值操作符
重载赋值操作符
赋值和复制一起使用
合成的复制构造函数和赋值操作符
定义自己的复制构造函数和赋值操作符
1 |
|