引用作为参数进行传递
如下代码:
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int MAX = 3;
void swap(int &a, int &b);
int _tmain(int argc, _TCHAR* argv[])
{
int c = 1, d = 4;
int &p1 = c;
int &p2 = d;
cout << "&p1" << &p1 << endl;
cout << "&p2" << &p2 << endl;
cout << "-----------" << endl;
swap(p1, p2);
cout << "p1=" << p1<<endl;
cout << "p2=" << p2 << endl;
cout << "-----------" << endl;
cout << "&p1" << &p1 << endl;
cout << "&p2" << &p2 << endl;
system("pause");
return 0;
}
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
return;
}
这个内存地址没变,只是内存里的值变了。
2、把引用作为返回值时
int& func() {
int q;
//! return q; // 在编译时发生错误
static int x;
return x; // 安全,x 在函数作用域外依然是有效的
}
注意static,和指针那个类似。