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;
}
本文详细介绍了构造函数的概念,包括构造函数、默认构造函数、拷贝构造函数及析构函数的特点与使用场景。并通过一个Teacher类的具体实例,展示了这些构造函数如何在C++中被定义和调用。
893

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



