对于构造函数来说,分为无参构造函数和有参构造函数,无参构造函数又可以叫做默认构造函数,而有参构造函数为两种参数,带默认值和参数无默认值。
- 拷贝构造函数定义格式:类名(const 类名 &变量名)
- 如果没有自定义的拷贝构造函数,则系统自动生成一个默认的拷贝构造函数
- 当采用直接初始化或复制初始化实例化对象时,系统自动调用拷贝构造函数
如果说构造函数是对象来到世间的第一声哭泣,那么虚构函数就是对象临终的遗言,析构函数在对象被销毁前自动调用,完成的任务是归还系统的资源,收拾最后的残局。
析构函数存在的必要性,例:
- 析构函数定义格式:~类名()
- 如果没有自定义的析构函数,则系统自动生成一个构造函数
- 虚构函数在对象销毁时自动调用
- 析构函数没有返回值,没有参数也不能重载
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;
}
总结:
类有成员函数和数据成员组成,如果担心自己定义的类于其他人定的类重名,可以在类之上再建立自己的命名空间。