C++中的构造函数、拷贝构造函数、析构函数

1、构造函数constructor
(1)构造函数的名字必须与类名相同;
(2)创建对象时自动调用的,且仅执行一-次 ;
(3)public ,无返回值,无需定义返回类型;
(4)允许重载,可以定义多个
(5)尽量简单,太复杂、包含大量逻辑处理的
(6)初始化工作建议用单独的Init()方法实现
(7)避免对象创建时出错
this是一个指针 ,指向对象自己

2、默认构造函数
在没有定义任何构造函数时,编译器会提供一个默认构造函数
·无参数,无任何代码
.一旦定义了任意一个构造函数,
·就不提供默认构造函数

3、拷贝构造函数

下列语句发生时,会执行拷贝构造函数:

这是对象需要通过另外一个对象进行初始化的一种情况

 Teacher t2 = t1;
 Teacher t3(t2);

4、析构函数
·函数的反函数
·格式public ~Time();
·无参数、无返回值
·不允许重载(只能有一个)
·销毁时自动调用,处理资源清理工作

代码:

Teacher.h

#include <string>
#include <iostream>
using namespace std;

class Teacher{
public:
	Teacher();//无参数构造函数
	Teacher(string n, int a);//有参数构造函数
	Teacher(const Teacher &tea); //拷贝构造函数
	~Teacher();//析构函数

	void setName(string);
	void setGender(string);
	void setAge(int);

	string getName();
	string getGender();
	int gerAge();
private:
	string name;
	string gender;
	int age;

};

 

Teacher.cpp

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

using namespace std;

Teacher::Teacher(const Teacher &tea) //拷贝构造函数
{
	cout << " Teacher::Teacher(const &tea)" << endl;//观察函数是否执行
}
Teacher::Teacher()//无参数构造函数
{
	cout << "无参数构造函数" << endl;  //观察函数是否执行
}
}
Teacher::Teacher(string n, int a)//有参数构造函数
{
	cout << "Teacher::Teacher(string n, int a)" << endl;
}
Teacher::~Teacher()//析构函数
{
	cout << "Teacher::~Teacher()//析构函数" << endl;  //观察函数是否执行
}
}



void Teacher::setName(string _name)
{
	name = _name;
}
string Teacher::getName()
{
	return name;
}
void Teacher::setGender(string _gender)
{
	gender = _gender;
}
string Teacher::getGender()
{
	return gender;
}
void Teacher::setAge(int _age)
{
	age = _age;
}
int Teacher::gerAge()
{
	return age;
}

main.cpp

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

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
 {
	Teacher t1;
	//Teacher t2 = t1; //为了测试拷贝构造函数的执行
	//Teacher t3(t2);//为了测试拷贝构造函数的执行
	Teacher *t2 = new Teacher();

	delete t2;
	t2 = NULL;
	
 	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值