關於C++函數思考2(函數返回引用和返回非引用的區別)

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.