
一和二在上篇文章(^ _ ^)
三.拷贝构造函数调用时机
C++中拷贝构造函数调用时机常常有三种情况:
(1).使用一个已经创建完毕的对象来初始化一个新对象。
(2)值传递的方式给函数参数传值。
(3)以值方式返回局部对象。
看不太懂捏,还是直接看代码罢:(^ - ^)
#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
Person(){
cout << "默认构造函数的调用" << endl;
}
Person(int a) {
cout << "含参构造函数的调用" << endl;
age = a;
}
Person(const Person& p)
{
cout << "拷贝构造函数的调用" << endl;
age = p.age;
}
~Person() {
cout << "析构函数的调用" << endl;
}
int age;
};
//(1).使用一个已经创建完毕的对象来初始化一个新对象。
void test01()
{
cout << 1 << endl;
Person a(10);
Person b(a);
cout << "b的年龄为: " << b.age << endl;
}
//(2)值传递的方式给函数参数传值。
void dowork(Person p)
{
//一个空实现
}
void test02() {
cout << 2 << endl;
Person c;
dowork(c);
}
//(3)以值方式返回局部对象。
Person dowork2()
{
Person p1;
cout << (int*)&p1 << endl;
return p1;
}
void test03() {
cout << 3 << endl;
Person p2= dowork2();
cout << (int*)&p2 << endl;
}
int main() {
test01();
test02();
test03();
system("pause");
return 0;
}
四.构造函数调用规则
默认情况下,c++编译器会给一个类自动添加三个函数
1.默认构造函数(无参,函数体为空)
2.默认析构函数(无参,函数体为空)
3.默认拷贝构造函数
构造函数的调用规则如下:
(1)如果用户提供默认析构函数,则编译器不会提供默认构造函数。
(2)若用户提供默认拷贝构造函数,则编译器不会提供其他构造函数
五.深拷贝与浅拷贝
浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
浅拷贝带来的问题就是堆区内存的重复释放
解决方法:利用深拷贝操作,
#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
Person(){
cout << "默认构造函数的调用" << endl;
}
Person(int a,int height) {
cout << "含参构造函数的调用" << endl;
age = a;
m_height = new int(height);
}
//自己实现拷贝函数解决浅拷贝带来的问题
Person(const Person& a)
{
cout << "person拷贝函数的调用" << endl;
age = a.age;
//m_height=p.m_height编译器自己实现
//深拷贝
m_height = new int(*a.m_height);
}
//堆区数据释放
~Person() {
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
cout << "析构函数的调用" << endl;
}
int age;
int* m_height;
};
void test01()
{
Person a(18,160);
cout << "a的年龄为: " << a.age << " 身高为: "<<*a.m_height<<endl;
Person b(a);
cout << "b的年龄为: " << b.age << " 身高为: " << *b.m_height << endl;
}
int main() {
test01();
system("pause");
return 0;
}
注意:如果在堆区开辟内存,记得在析构函数中把堆区内存释放
如果属性有在堆区开辟的,记得自己提供拷贝构造函数
1252

被折叠的 条评论
为什么被折叠?



