C++ 有关赋值构造函数 拷贝构造函数 自动型别转换

#include <iostream>
using namespace std;

class T
{
	private:
		int num;
	public:
		T():num(0) {cout << "In T(): num = " << num << endl;}
		T(int size):num(size) {cout << "In T(int): num = " << num << endl; }
		T(const T &t) {cout << "In T(const T &)" << endl;}
		void setNum(int num) {this->num = num;}
		~T() {cout << "In ~T():num = " << num << endl; }
		T &operator = (const T &t) {cout << "In =" << endl;}
};

void f(T t) {cout << "In f" << endl;};

int main()
{

	f(10);       //调用 T(int size)构造函数生成一个对象,这个对象在f函数结束时调用析构函数释放 
	T t;//调用 T()构造函数 
	t = 40;//先通过40自动型别转换调用T(int size)生成一个临时对象,然后调用T &operator = (const T &t)赋值构造函数,然后临时对象释放调用析构函数 
	t.setNum(12);
	
	T s = 88;//通过自动型别转换 用T(int size)生成s对象 
	cout << "aaaa" << endl;
	
	return 0;
	//调用s的析构函数,然后调用t的析构函数 
}


输出:

In T(int): num = 10
In f
In ~T():num = 10
In T(): num = 0
In T(int): num = 40
In =
In ~T():num = 40
In T(int): num = 88
aaaa
In ~T():num = 88
In ~T():num = 12

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值