C++中的一类临时对象

类名(参数名)这样的对象是临时对象,不能取地址,不能被引用,不过可以给同类型的其他对象赋值,该临时对象定以后可以进行一次操作,然后立即销毁。

当我们定义一个对象以后并不想立即给它赋初值,而是以后给它赋初值,在稍后赋初值的时候,该类临时对象就可以发挥作用了。

下面给出一个例子:

#include<iostream>
#include<string>
using namespace std;
class A
{
	public:
		A()
		{
			cout<<"Default constructor"<<endl;
		}
		A(string n)
		{
			name = n;
			cout<<"Constructor called=====>"<<name<<endl;
		}
		~A()
		{
			cout<<"Desctructor called=======>"<<name<<endl;
		}
	private:
		string name;
};
int main()
{
	A a;
	a =A("one");
	return 0;
}

结果输出:

Default constructor
Constructor called=====>one
Desctructor called=======>one
Desctructor called=======>one

用于对象数组初始化的有趣情况:

当临时对象用于数组对象初始化的时候,有两种情况:

情况一:使用初始化表统一进行初始化

#include<iostream>
#include<string>
using namespace std;
class A
{
	public:
		A()
		{
			cout<<"Default constructor"<<endl;
		}
		A(string n)
		{
			name = n;
			cout<<"Constructor called=====>"<<name<<endl;
		}
		~A()
		{
			cout<<"Desctructor called=======>"<<name<<endl;
		}
	private:
		string name;
};
int main()
{
	A a[2]={A("ONE"),A("TWO")};
	return 0;
}

结果输出:

Constructor called=====>ONE
Constructor called=====>TWO
Desctructor called=======>TWO
Desctructor called=======>ONE

情况二:单独进行初始化

#include<iostream>
#include<string>
using namespace std;
class A
{
	public:
		A()
		{
			cout<<"Default constructor"<<endl;
		}
		A(string n)
		{
			name = n;
			cout<<"Constructor called=====>"<<name<<endl;
		}
		~A()
		{
			cout<<"Desctructor called=======>"<<name<<endl;
		}
	private:
		string name;
};
int main()
{
	A a[2];
	a[0]=A("one");
	a[1]=A("two");
	return 0;
}

输出结果:



转换构造函数会生成临时变量:

示例代码:

情况一:在定义对象时用数字初始化:

#include<iostream>
using namespace std;
class A
{
	public:
		A(int i = 0)
		{
			m = i;
			cout<<"Constructor called."<<m<<endl;
		}
		void set(int i)
		{
			m = i;
		}
		void print()
		{
			cout<<m<<endl;
		}
		~A()
		{
			cout<<"Destructor called."<<m<<endl;
		}
	private:
		int m;
};
int main()
{
	A my = 5;
	my.print();
	return 0;
}

结果输出:


情况二:定义好对象以后再使用数字进行赋值

#include<iostream>
using namespace std;
class A
{
	public:
		A(int i = 0)
		{
			m = i;
			cout<<"Constructor called."<<m<<endl;
		}
		void set(int i)
		{
			m = i;
		}
		void print()
		{
			cout<<m<<endl;
		}
		~A()
		{
			cout<<"Destructor called."<<m<<endl;
		}
	private:
		int m;
};
int main()
{
	A my;
	my = 5;
	my.print();
	return 0;
}

结果输出:



posted @ 2014-01-03 00:29  千手宇智波  阅读(377)  评论(0编辑  收藏  举报