定义
拷贝构造函数是一种特殊的构造函数,它在创建对象时,是使用同一类中之前创建的对象来初始化新创建的对象。
拷贝构造函数通常用于:
- 通过使用另一个同类型的对象来初始化新创建的对象。
- 复制对象把它作为参数传递给函数。
- 复制对象,并从函数返回这个对象。
如果在类中没有定义拷贝构造函数,编译器会自行定义一个。如果类带有指针变量,并有动态内存分配,则它必须有一个拷贝构造函数。拷贝构造函数的最常见形式如下:
//在这里,obj 是一个对象引用,该对象是用于初始化另一个对象的。
classname (const classname &obj) {
// 构造函数的主体
}
三种用法
通过使用已有的同类型的对象来初始化新创建的对象:
#include<iostream>
using namespace std;
class CExample
{
private:
int a;
public:
//构造函数
CExample(int b)
{
a=b;
printf("constructor is called\n");
}
//拷贝构造函数
CExample(const CExample & c)
{
a=c.a;
printf("copy constructor is called\n");
}
//析构函数
~CExample()
{
cout<<"destructor is called\n";
}
void Show()
{
cout<<a<<endl;
}
};
int main()
{
CExample A(100);
CExample B=A;
B.Show();
return 0;
}
将会输出下面的结果:
constructor is called
copy constructor is called
100
destructor is called
destructor is called
当函数的参数为类的对象时
下面我们看示例代码中拷贝构造函数自动被调用:
#include<iostream>
using namespace std;
class CExample
{
private:
int a;
public:
CExample(int b)
{
a=b;
cout<<"constructor is called\n";
}
CExample(const CExample & c)
{
a=c.a;
cout<<"copy constructor is called\n";
}
~CExample()
{
cout<<"destructor is called\n";
}
void Show()
{
cout<<a<<endl;
}
};
void g_fun(CExample c)
{
cout<<"g_func"<<endl;
}
int main()
{
CExample A(100);
CExample B=A;
B.Show();
g_fun(A);
return 0;
}
上面的代码执行会打印下面的结果:
constructor is called
copy constructor is called
100
copy constructor is called
g_func
destructor is called
destructor is called
destructor is called
其调用过程如下:
调用g_fun()时,会产生以下几个重要步骤:
(1).A对象传入形参时,会先会产生一个临时变量,就叫 C 吧。
(2).然后调用拷贝构造函数把A的值给C。 整个这两个步骤有点像:CExample C(A);
(3).等g_fun()执行完后, 析构掉 C 对象。
函数的返回值是类的对象
#include<iostream>
using namespace std;
class CExample
{
private:
int a;
public:
//构造函数
CExample(int b)
{
a=b;
printf("constructor is called\n");
}
//拷贝构造函数
CExample(const CExample & c)
{
a=c.a;
printf("copy constructor is called\n");
}
//析构函数
~CExample()
{
cout<<"destructor is called\n";
}
void Show()
{
cout<<a<<endl;
}
};
CExample g_fun()
{
CExample temp(0);
return temp;
}
int main()
{
g_fun();
return 0;
}
当g_Fun()函数执行到return时,会产生以下几个重要步骤:
(1). 先会产生一个临时变量,就叫XXXX吧。
(2). 然后调用拷贝构造函数把temp的值给XXXX。整个这两个步骤有点像:CExample XXXX(temp);
(3). 在函数执行到最后先析构temp局部变量。
(4). 等g_fun()执行完后再析构掉XXXX对象。
输出如下:
浅拷贝、深拷贝、防止默认拷贝
请参考博客:c++拷贝构造函数详解
https://www.cnblogs.com/alantu2018/p/8459250.html