拷贝构造函数的三种使用情况
拷贝构造函数是构造函数的一种,也称拷贝构造函数,它只有一个参数,参数类型是本类的引用。
下面是该函数调用的三种情况:
- 使用一个已经创建完毕的对象来初始化一个新对象。
- 以函数值传递的方式给函数参数传值。
- 以函数值方式返回局部对象。
具体示例如下:
1.使用一个已经创建完毕的对象来初始化一个新对象。
Person p1(20);//调用有参构造函数
Person p2(p1);//使用已创建的p1初始化新对象p2,调用拷贝构造函数
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数调用"<<endl;
}
Person(int age)
{
cout << "有参构造函数调用" << endl;
m_age = age;
}
Person(const Person & p)
{
cout << "拷贝构造函数调用" << endl;
m_age = p.m_age;
}
~Person()
{
cout << "析构函数调用"<<endl;
}
int m_age;
};
void test01()
{
Person p1(20);//调用有参构造函数
Person p2(p1);//使用已创建的p1初始化新对象p2,调用拷贝构造函数
}
int main()
{
test01();
return 0;
}
结果如下所示:
2.以函数值传递的方式给函数参数传值。
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数调用" << endl;
}
Person(int age)
{
cout << "有参构造函数调用" << endl;
m_age = age;
}
Person(const Person& p)
{
cout << "拷贝构造函数调用" << endl;
m_age = p.m_age;
}
~Person()
{
cout << "析构函数调用" << endl;
}
int m_age;
};
void dowork(Person)
{
}
void test02()
{
Person p;//这里调用默认无参构造函数
dowork(p);//这里把p传给函数dowork(Person)的形参,调用了拷贝构造函数
}
int main()
{
test02();
return 0;
}
结果如下:
Person p;//这里调用默认无参构造函数
dowork§;//这里把p传给函数dowork(Person)的形参,调用了拷贝构造函数
3.以函数值方式返回局部对象。
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数调用" << endl;
}
Person(int age)
{
cout << "有参构造函数调用" << endl;
m_age = age;
}
Person(const Person& p)
{
cout << "拷贝构造函数调用" << endl;
m_age = p.m_age;
}
~Person()
{
cout << "析构函数调用" << endl;
}
int m_age;
};
Person dowork2()
{
Person p1;//这里调用默认无参构造函数
cout << (int*)&p1 << endl;
return p1;
}
void test03()
{
Person p = dowork2();//函数返回的Person类对象p1来初始化p,这里调用了拷贝构造函数
cout << (int*)&p << endl;//注意p和p1地址并不相同
}
int main()
{
test03();
return 0;
}
结果如下:
Person p = dowork2();//函数返回的Person类对象p1来初始化p,这里调用了拷贝构造函数
以上是我在b站学习黑马程序员的c++时所做笔记及总结,如有不正确的地方欢迎大家指教,谢谢!