函数的调用与优化实例

函数的调用与优化实例
-------------------------------------------------------------------------------------------------------------------------

 #include<iostream>
    using namespace std;
    class Test
    {
    public:
    	Test (int d=0):data(d)
    	{
    		cout<<"create test object:"<<this<<endl;
    	}
    	Test (const Test &t)
    	{
    		cout<<"copy create test object:"<<this<<endl;
    		data=t.data;
    	}
    	Test &operator=(const Test &t)
    	{
    		if(this!=&t)
    		{
    			data=t.data;
    		}
    		return *this;
    	}
    	~Test()
    	{
    		cout<<"free test object:"<<this<<endl;
    	}
    public:
    	int GetData()const
    	{
    		return data;	
    	}
    private:
    	int data;
    
    };
    //4
    Test fun(Test &x)
     {
    	 int value=x.GetData();
    	 return Test(value);//创建无名临时对象语法
     }
     
     void main()
     {
    	 Test t1(100);
    	 Test  t2=fun(t1);
    	
     }
    /*
    //3
    Test &fun(Test &x)
     {
    	 int value=x.GetData();
    	 return Test(value);//创建无名临时对象语法
     }
     
     void main()
     {
    	 Test t1(100);
    	 Test t2;
    	 t2=fun(t1);
     }
     */
    /*
    //2  比//1要优化
    Test fun(Test &x)
     {
    	 int value=x.GetData();
    	 return Test(value);//创建无名临时对象语法
     }
     
     void main()
     {
    	 Test t1(100);
    	 Test t2;
    	 t2=fun(t1);
     }
     */
    /*
    //1
     Test fun(Test x)
     {
    	 int value=x.GetData();
    	 Test tmp(value);
    	 return tmp;
     }
     
     void main()
     {
    	 Test t1(100);
    	 Test t2;
    	 t2=fun(t1);
     }
    */

猜你喜欢

转载自blog.csdn.net/weixin_41747893/article/details/87949154