Differenct between return by value and by reference

类别:编程语言 点击:0 评论:0 推荐:

Consider the following code:

//==================================
1    int max( int& n1, int& n2 )
2    {
3      if(n1>n2)
4         return n1 ;
5      else
6        return n2 ;
7    }

8    void main()
9    {
10    int x=1, y=2 ;
11    max( x,y ) = 5 ;
      }
//===================================

The can not be complier. Because in line 11, a value is returned which is a const. A const cannot be assigned a new value.

However, if we changed the code in line1 to

int&  max(int& n1, int& n2)

The code can be complied and exectuted! Because a reference has been returned, which is either x or y in the main function. That is, returend reference is a variable. Assign a value to a variable is legal.

本文地址:http://com.8s8s.com/it/it22562.htm