Test.h
#ifndef _TEST_H_
#define _TEST_H_
class Test
{
public:
Test(); //构造函数:主要用来初始化函数
//特点:1) 函数名和类名完全相同
// 2) 不能定义构造函数的返回类型,也不能用void
// 3) 应声明为公有函数,使其能够被调用
// 4) 可以有任意类型和任意个数的参数,一个类可有多个构造函数(重载)
// 5) 全局对象的构造函数先于 main函数
// (该类就有2个,其中无参数的称为:默认构造函数)
// (如果未声明默认构造函数,系统会自动产出一个默认构造函数)
//执行时间:在类对象被声明时立即自动调用
Test(int x, int y, int z);//构造函数重载:虽然函数名相同,但由于
//参数的 个数、类型、顺序 不同,会系统会将这些
//函数名相同的函数进行重新命名,从而根据参数进行识别
~Test();//析构函数:不能有参数
//特点:1) 函数名和类名相同,前面多一个‘~’
// 2) 没有返回类型
// 3) 没有参数
// 4) 不能被重载
// 5) 如果没有定义,系统会自动生成一个默认析构函数,其是一个空函数
//执行时间:在类对象被释放时调用
private:
int x_;
int y_;
int z_;
};
#endif
Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;
Test::Test()
{
cout << "Initializing default" << endl;
}
Test::Test(int x, int y, int z)
{
x_ = x;
y_ = y;
z_ = z;
cout << "Initliazing " << endl;
cout << "x_ = "<< x_ << "\t";
cout << "y_ = "<< y_ << "\t";
cout << "z_ = "<< z_ <<endl;
}
Test::~Test()
{
cout << "Destory test" << endl;
}
Main.cpp
#include "Test.h"
using namespace std;
Test t0; //全局对象的构造函数先于 main 函数
int main()
{
cout << "main function" << endl;
Test t1;
Test t2(1, 2, 3);
Test * t3 = new Test(4, 5, 6); //初始化 t3 (此时会调用构造函数)
delete t3; //释放 t3 (此时会调用析构函数)
cout << "Delete end" << endl;
return 0;
}
结果为:
总结:1) 构造函数在定义对象时立即调用 (主要用来初始化对象)
2) 析构函数在释放对象时调用