构造函数的调用规则

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

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

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

3、默认拷贝构造函数,对属性进行值拷贝

构造函数的调用规则如下:

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

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

// 构造函数的调用规则.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;

//构造函数的调用规则
class Person
{
public:

	Person()
	{
		cout << "Person的默认构造函数调用" << endl;
	}
	Person(int age)
	{
		cout << "Person的有参构造函数调用" << endl;
		
	}
	Person(const Person& p)
	{
		cout << "Person的拷贝构造函数调用" << endl;
		m_Age = p.m_Age;
	}
	~Person()
	{
		cout << "Person的析构函数调用" << endl;
	}

	int m_Age;
};
void test01()
{
	Person p;
	p.m_Age = 18;

	Person p2(p);

	cout << "p2的年龄为: " << p2.m_Age << endl;
}
int main()
{
	test01();
	system("pause");

	return 0;
}


此时的输出如下

如果我们把拷贝函数注释掉

此时我们看到p2的值仍然为18,说明类里有一个默认拷贝参数

// 构造函数的调用规则.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;

//构造函数的调用规则
class Person
{
public:

	//Person()
	//
		//cout << "Person的默认构造函数调用" << endl;
	//}
	Person(int age)
	{
		cout << "Person的有参构造函数调用" << endl;
		
	}
	Person(const Person& p)
	{
		m_Age = p.m_Age;
	}
	~Person()
	{
		cout << "Person的析构函数调用" << endl;
	}

	int m_Age;
};
void test01()
{
	Person p;
	p.m_Age = 18;

	Person p2(p);

	cout << "p2的年龄为: " << p2.m_Age << endl;
}
void test02()
{
	Person p;
}
int main()
{
	//test01();
	test02();
	system("pause");

	return 0;
}


此时会报错,因为当我们定义了一个有参构造函数就不在提供默认构造函数,所以会发生报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值