Test.h
#ifndef _TEST_H_
#define _TEST_H_
class Test
{
public:
Test();
Test(int num); //转换构造函数:单个参数的构造函数
//作用:将其他类型转数据换为类类型
~Test();
private:
int num_;
};
#endif
Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;
Test::Test()
{
cout << "Initlizing default" << endl;
}
Test::Test(int num)
{
num_ = num;
cout << "num_ = " << num_ << endl;
}
Test::~Test()
{
cout << "Destory test " << num_ << endl;
}
Main.cpp
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test t1(10); //带一个参数的构造函数,充当普通构造函数的功能
t1 = 20; //将20这个整数赋给 t 对象
//1) 调用转换构造函数将20这个整数转换为类类型(生成一个临时对象)
//2)将临时对象赋值给 t 对象(调用的是 = 运算符)
Test t2;
return 0;
}
结果:
总结:结果中,t1运行后即调用了析构函数,可知 t1 = 20;中生成了一个临时对象,完成赋值任务后直接释放,所以该处的析构函数先于 Test t2; 的默认构造函数。