C++中的引用-引用做函式引數和引用做函式返回值
阿新 • • 發佈:2021-07-26
- 引用做函式引數
- 總結:通過引用引數產生的效果同按地址傳遞是一樣的。引用的語法更清楚簡單
點選檢視程式碼
#include<iostream> #include<string> using namespace std; //交換函式 //1、值傳遞 (形參不會修飾實參) void mySwap01(int a, int b) { int tmp = a; a = b; b = tmp; cout << "mySwap01 a = " << a << endl; cout << "mySwap01 b = " << b << endl; } //2、地址傳遞 (形參會修飾實參) void mySwap02(int* p, int* q) { int tmp = *p; *p = *q; *q = tmp; cout << "mySwap02 p = " << *p << endl; cout << "mySwap02 q = " << *q << endl; } //3、引用傳遞 (形參會修飾實參) void mySwap03(int &m, int &n) { int tmp = m; m = n; n = tmp; cout << "mySwap03 m = " << m << endl; cout << "mySwap03 n = " << n << endl; } int main() { int a = 10; int b = 20; mySwap01(a, b); //值傳遞,形參不會修飾實參 cout << "a = " << a << endl; cout << "b = " << b << endl; int p = 30; int q = 40; mySwap02(&p, &q); //地址傳遞,形參會修飾實參 cout << "p = " << p << endl; cout << "q = " << q << endl; int m = 50; int n = 60; mySwap03(m, n); //引用傳遞,形參會修飾實參 cout << "m = " << m << endl; cout << "n = " << n << endl; system("pause"); return 0; }