引用是提高代码效率的一大利器,尤其对于对象来说,当引用作为参数时候不用大面积的复制对象本身所造成的空间与时间的浪费。所以有时候对于参数的返回值我们也希望返回参数的引用。在这里我们回忆一下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>
下来总结一下返回引用和非引用:
时间: 2024-10-12 10:56:28