標籤:
引用是提高代碼效率的一大利器,尤其對於對象來說,當引用作為參數時候不用大面積的複製對象本身所造成的空間與時間的浪費。所以有時候對於參數的返回值我們也希望返回參數的引用。在這裡我們回憶一下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>
下來總結一下返回引用和非引用:
關於C++函數思考2(函數返回引用和返回非引用的區別)