构造函数调用规则

文章讲述了C++编译器在生成类时的行为,包括默认构造函数、析构函数和拷贝构造函数的添加规则。如果有参构造或拷贝构造被定义,编译器将不再提供默认版本。
摘要由CSDN通过智能技术生成

默认情况下,c++编译器至少给一个类添加3个函数

1.默认构造函数(无参,函数体为空)

2.默认析构函数(无参,函数体为空)

3.默认拷贝构造函数,对属性进行值拷贝(“=”号赋值)

构造函数调用规则如下:

如果用户定义了有参构造函数,c++不再提供默认无参构造,但是会提供默认拷贝构造

如果用户定义了拷贝构造函数,c++不会再提供其他构造函数

#include<iostream>
using namespace std;

//构造函数的调用规则
//1.创建一个类,C++编译器会给每个类都添加至少三个函数
//默认构造(空实现)
//析构函数(空实现)
//拷贝函数(值拷贝)

class Person
{
public:
	Person()
	{
		cout << "Person的默认构造函数调用" << endl;
	}

	Person(int age)
	{
		cout << "Person的有参构造函数调用" << endl;
		m_Age = age;
	}

	Person(const Person &p)
	{
		cout << "Person的拷贝构造函数调用" << endl;
		m_Age = p.m_Age;
	}

	~Person()
	{
		cout << "Person的析构函数调用" << endl;
	}

	int m_Age;
};

void test1()
{	
    Person p;
	p.m_Age = 18;

	Person p2(p);
	cout << "p2的年龄为:" <<p2.m_Age<< endl;
}

int main()
{
	test1();

	return 0;
}
out:
Person的默认构造函数调用
Person的拷贝构造函数调用
p2的年龄为:18
Person的析构函数调用
Person的析构函数调用

 若将拷贝函数注释,则得到以下结果:

out:
Person的默认构造函数调用
p2的年龄为:18
Person的析构函数调用
Person的析构函数调用

 编译器自动提供的拷贝构造函数会执行以下代码,做一个值拷贝操作,即:

m_Age = p.m_Age;

 将p的所有属性做一个等号赋值的操作。所有打印的p2年龄为18

#include<iostream>
using namespace std;

//2.
// 如果我们写了有参构造函数,编译器就不再提供默认构造函数但依然提供拷贝构造函数
// 如果我们写了拷贝构造函数,编译器就不再提供其他构造函数

class Person
{
public:
	//Person()
	//{
	//	cout << "Person的默认构造函数调用" << endl;
	//}

	Person(int age)
	{
		cout << "Person的有参构造函数调用" << endl;
		m_Age = age;
	}

	//Person(const Person &p)
	//{
	//	cout << "Person的拷贝构造函数调用" << endl;
	//	m_Age = p.m_Age;
	//}

	~Person()
	{
		cout << "Person的析构函数调用" << endl;
	}

	int m_Age;
};


void test2()
{
	Person p(20);

	Person p2(p);
	cout << "p2的年龄为:" << p2.m_Age << endl;
}

int main()
{
	test2();

	return 0;
}
out:
Person的有参构造函数调用
p2的年龄为:20
Person的析构函数调用
Person的析构函数调用

总结:默认-->有参-->拷贝,一个比一个高级,定义了其中一个,编译器则不提供之前的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值