关于C++函数思考2(函数返回引用和返回非引用的区别)

      引用是提高代码效率的一大利器,尤其对于对象来说,当引用作为参数时候不用大面积的复制对象本身所造成的空间与时间的浪费。所以有时候对于参数的返回值我们也希望返回参数的引用。在这里我们回忆一下C语言函数返回局部变量所注意的方面,也可以看我的这篇文章。下来我们对于C++ 中函数返回引用或非引用进行探讨!!

1.返回引用


/**********************************************************************    
* *   Copyright (c)2015,WK Studios  
* *   Filename:  A.h
* *   Compiler: GCC  vc 6.0   
* *   Author:WK    
* *   Time: 2015 4 5  
* **********************************************************************/
#include<iostream>

using std::cout;
using std::cin;
class Test
{
public:
	Test(int d=0):m_data(d)
	{
		cout<<"Create Test Obj :"<<this<<"\n";
	}
	Test(const Test &t)
	{
		cout<<"Copy Test Obj : "<<this<<"\n";
		m_data = t.m_data;
	}
	Test& operator=(const Test &t)
	{
		cout<<"Assgin:"<<this<<" : "<<&t<<"\n";
		if(this != &t)
		{
			m_data = t.m_data;
		}
		return *this;
	}
	~Test()
	{
		cout<<"Free Test Obj :"<<this<<"\n";
	}
	int GetData()const
	{
		return m_data;
	}
	void print()
	{
		cout<<m_data<<"\n";
	}
private:
	int m_data;
};
//方式一
Test& fun(const Test &t)
{
	int value = t.GetData();
	Test tmp(value);
	return tmp;
}

void main()
{
	Test t(10);
	
	Test t1;
	t1 = fun(t);
	cout<<"m_data of t1 is: ";
	t1.print();
	
	Test t2 = fun(t);
	cout<<"m_data of t2 is: ";
	t2.print();
}
技术分享


技术分享

2.返回非引用

<span style="color:#333333;">/**********************************************************************    
* *   Copyright (c)2015,WK Studios  
* *   Filename:  A.h
* *   Compiler: GCC  vc 6.0   
* *   Author:WK    
* *   Time: 2015 4 5  
* **********************************************************************/
#include<iostream>

using std::cout;
using std::cin;
class Test
{
public:
	Test(int d=0):m_data(d)
	{
		cout<<"Create Test Obj :"<<this<<"\n";
	}
	Test(const Test &t)
	{
		cout<<"Copy Test Obj : "<<this<<"\n";
		m_data = t.m_data;
	}
	Test& operator=(const Test &t)
	{
		cout<<"Assgin:"<<this<<" : "<<&t<<"\n";
		if(this != &t)
		{
			m_data = t.m_data;
		}
		return *this;
	}
	~Test()
	{
		cout<<"Free Test Obj :"<<this<<"\n";
	}
	int GetData()const
	{
		return m_data;
	}
	void print()
	{
		cout<<m_data<<"\n";
	}
private:
	int m_data;
};
//方式一
Test fun(const Test &t)
{
	int value = t.GetData();
	Test tmp(value);
	return tmp;
}

void main()
{
	Test t(10);

	Test t1;
	t1 = fun(t);
	cout<<"m_data of t1 is: ";
	t1.print();


	Test t2 = fun(t);
	cout<<"m_data of t2 is: ";
	t2.print();

}
</span>
技术分享
技术分享

下来总结一下返回引用和非引用:

技术分享


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。