C++构造函数和析构函数初步认识(2)

构造函数的三个作用
1.构造对象
2.对象初始化
3.类型转换 

//Test1.h
#include<iostream>
using namespace std;
//构造对象
//初始化对象
//类型装换
class ST
{
private:
	int a;
	long b;
public:
	ST(int a=0);//缺省的构造函数只允许有一个
	ST(long b);
	ST(int a, long b);
	~ST()
	{
		cout<<"ST was Free. "<<this<<endl;
	}
	operator int();
	operator long();
	int Get_a();
	void fill(int a, long b);
};
ST::ST(int a)
{
	cout<<"ST was Built. "<<this<<endl;
	this->a = a;
}
ST::ST(int a, long b)
{
	cout<<"ST was Built. "<<this<<endl;
	this->a = a;
	this->b = b;
}
ST::ST(long b)
{
	cout<<"ST was Built. "<<this<<endl;
	this->b = b;
}
ST::operator int()
{
	return this->a;
}
ST::operator long()
{
	return this->b;
}
int ST::Get_a()
{
	return this->a;
}
void ST::fill(int a, long b)
{
		this->a = a;
		this->b = b;
}

 

//Test.cpp
#include<iostream>
#include"Test1.h"
using namespace std;
void main()
{
	ST st;
	int a1,a2,a = 100;
	long b1,b = 1000;
	st = a;//此处为一个隐式转换,产生了一个中间变量,构造函数使a转换为ST类型,然后用此中间变量给st.a赋值
			//这样的强制转换是对构造函数有要求的,若构造函数无参数或者其参数有多个则不能进行转换
	a = 101;//值得关注的一个问题是,a被构造函数转换并赋值给st.a后,其便会被析构掉,不需要等到程序结束
	st = (ST)a;//也可以将其显式的写出来,只要其构造函数无explicit前缀,则显式隐式都可以,若含有exitplic前缀则必须显式类型转换
	st = b;//有两个重载的构造函数可以进行转换,转化时系统可由构造函数参数列表自动识别为其选择构造函数
		   //由于是st接收转换类型后的b值,若构造函数内仅对一个私有数据成员进行赋值,则其他私有成员皆为随机值
			//这也就是为何st先接收a的赋值,再接收b的赋值后其私有数据成员st.a变为随机值的原因
	
	st.fill(10,20);
	a1 = st;//C++没有默认的从对象到数据类型的转换,若想要转换则必须写一个方法,或者使用operator将类型转换的方法写出来
	a2 = st.Get_a();//此方法和上一行的代码效果相同
	b1 = st;
	cout<<"a1 = "<<a1<<" a2 = "<<a2<<endl;
	cout<<"b1 = "<<b1<<endl;
}

  运行结果

 

转载于:https://www.cnblogs.com/area-h-p/p/10318836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值