要以引用返回函數值,則函數定義時的格式如下:
類型標識符&類型名 (形參列表及類型說明)
{ 函數體 }
用const限定引用的聲明方式為:
const 類型標識符&引用名=目標變量名;
用這種方式聲明的引用不能通過引用對目標變量的值進行修改,從而使引用的目標成為const,保證了 引用的安全性。
注意幾點:
本人自學,教材可能有點老,有問題的話求大家指正!!!謝謝!!!
例題:
1 #include<iostream>
2 using namespace std;
3
4
5 int f1(int a);
6 int &f2(int a);
7
8 int f1(int a)
9 {
10 int num;
11 num = a*10;
12 return num;
13 }
14
15 int &f2(int a)
16 {
17 int num;
18 num = a*20;
19 return num;
20 }
21
22 int main()
23 {
24 int a,b;
25 a=f1(1);
26 b=f2(2);
27 cout << f1(4) << endl;
28 cout << f2(5) << endl;
29 cout << a << endl;
30 cout << b << endl;
31 //int &ra=f1(3); 這種用法可能會出錯,(不同C++系統有不同規定)
32 int &rb=f2(3);
33 cout << rb << endl;
34 return 0;
35 }
1 #include<iostream>
2 using namespace std;
3
4 int &put(int n);
5 int vals[10];
6 int error=-1;
7
8
9 int &put(int n)
10 {
11 if(n>=0 && n<=9)
12 return vals[n];
13 else
14 {
15 cout << "error!" << endl;
16 return error;
17 }
18 }
19
20 int main()
21 {
22 put(0)=10;
23 put(9)=20;
24 cout << vals[0] << endl;
25 cout << vals[9] << endl;
26 return 0;
27 }
1 include<iostream>
2 using namespace std;
3
4 int &fn(const int &a)
5 {
6 //a=32; 錯誤!不可以進行賦值
7 int b=a;
8 return b; //如果返回a,也會報錯
9 }
10
11 int main()
12 {
13 int &a = fn(32);
14 cout << a << endl;
15 return 0;
16 }
17
18 //菜鳥,求大家批評指教,代碼編寫習慣和規范等等!!!謝謝!!!
本人自學,教材可能有點老,有問題的話求大家指正!!!謝謝!!!