【c++】实验说明“转换构造函数”是如何转换的

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; 的默认构造函数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值