定义:是一种特殊的构造函数。用同类的旧的对象初始化新的对象。
classname (const classname &obj) {
// 构造函数的主体
}
比如说
Line( const Line &obj);//Line是class名字
obj 是一个旧对象引用,该旧对象是用于初始化新对象的。
Line::Line(const Line &obj)
{
cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl;
ptr = new int;
*ptr = *obj.ptr; // 拷贝值
}
#include <iostream>
using namespace std;
class Line
{
public:
int getLength(void);
Line(int len); // 简单的构造函数
Line(const Line &obj); // 拷贝构造函数
~Line(); // 析构函数
private:
int *ptr;
};
// 成员函数定义,包括构造函数
Line::Line(int len)
{
cout << "调用构造函数" << endl;
// 为指针分配内存
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl;
ptr = new int;
*ptr = *obj.ptr; // 拷贝值
}
Line::~Line(void)
{
cout << "释放内存" << endl;
delete ptr;
}
int Line::getLength(void)
{
return *ptr;
}
void display(Line obj)//这个地方Line 是用的拷贝构造函数
{
cout << "line 大小 : " << obj.getLength() << endl;
}
// 程序的主函数
int main()
{
Line line1(10);//调用构造函数
Line line2 = line1; // 这里也调用了拷贝构造函数
display(line1);//调用拷贝构造函数并为指针 ptr 分配内存 line 大小 : 10 释放内存,为什么这个地方造成了构造函数
display(line2);//调用拷贝构造函数并为指针 ptr 分配内存 line 大小 : 10 释放内存
return 0;
}