您的位置:首页 > 编程语言 > C语言/C++

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

2012-11-25 23:51 225 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: