如何分别调用无参构造函数和析构函数_C++拷贝构造函数和析构函数

对于构造函数来说,分为无参构造函数和有参构造函数,无参构造函数又可以叫做默认构造函数,而有参构造函数为两种参数,带默认值和参数无默认值。

5221955b170a0d67120cd7411fdce4fb.png

8aa35362068f915b6286b860edc2d828.png
  • 拷贝构造函数定义格式:类名(const 类名 &变量名)
  • 如果没有自定义的拷贝构造函数,则系统自动生成一个默认的拷贝构造函数
  • 当采用直接初始化或复制初始化实例化对象时,系统自动调用拷贝构造函数

如果说构造函数是对象来到世间的第一声哭泣,那么虚构函数就是对象临终的遗言,析构函数在对象被销毁前自动调用,完成的任务是归还系统的资源,收拾最后的残局。

析构函数存在的必要性,例:

1dffff71736706223358531cdbbe99f1.png
  • 析构函数定义格式:~类名()

02fe9bcaee234562dfeb77b2cfa8df0d.png
  • 如果没有自定义的析构函数,则系统自动生成一个构造函数
  • 虚构函数在对象销毁时自动调用
  • 析构函数没有返回值,没有参数也不能重载

d176a160148bafe0834479575af9abcc.png

Teacher.h

#include <iostream>
#include <string>
using namespace std;
class Teacher
{
public:
	//构造函数
	Teacher(string name ="Jim", int age = 18);
	//拷贝构造函数
	Teacher(const Teacher &t);
	//析构函数
	~Teacher();
	void SetName(string name);
	string GetName();
	void SetAge(int age);
	int GetAge();

private:
	string m_strName;
	int m_iAge;
};

Teacher.cpp

#include <iostream>
#include <string>
#include "Teacher.h"

Teacher::Teacher(string name, int age) :m_strName(name), m_iAge(age)
{
	cout << "Teacher(string name, int age)" << endl;
}

Teacher::Teacher(const Teacher &t) 
{
	cout << "Teacher::Teacher(const Teacher &t) " << endl;
}

Teacher::~Teacher()
{
	cout << "~Teacher()" << endl;
}

void Teacher::SetName(string name)
{
	m_strName = name;
}

string Teacher::GetName()
{
	return m_strName;
}

void Teacher::SetAge(int age)
{
	m_iAge = age;
}

int Teacher::GetAge()
{
	return m_iAge;
}

main.cpp

#include <iostream>
#include <string>
#include "Teacher.h"
/**************************************
Teacher类:自定义拷贝构造函数
数据:名字,年龄
成员函数:数据成员的封装函数
自定义虚构函数,普通方式实例化的对象在销毁对象时是否自动调用析构函数?
通过拷贝构造函数实例化对象在销毁对象时是否调用析构函数?
**************************************/
int main1()
{
	Teacher t1;
	Teacher t2 = t1;
	Teacher t3(t1);
	system("pause");
	return 0;
}
int main()
{	
	//从栈中实例化一个对象
	Teacher t1;
	Teacher *p =new Teacher();
	delete p;
	p = NULL;
	cout << "**********************" << endl;
	Teacher t2 = t1;
	
	system("pause");
	return 0;
}

808bf5fdfbadaa6619afcb7d3b4da172.png

总结:

类有成员函数和数据成员组成,如果担心自己定义的类于其他人定的类重名,可以在类之上再建立自己的命名空间。

214ac7952475c05feade53288b9e4e88.png

50194df42df2f3279f804e668a816974.png

8986109d76f95846d9dfc53280e29638.png
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值