引用
#include <iostream> //01ref.cpp
using namespace std;
void swap(int *pa,int *pb){
int tmp = *pa;//pa = &a;
*pa = *pb;
*pb = tmp;
}
//引用
void exchange(int& m,int& n){// m和n是实参a和b的别名 操作m和n 其实 就是操作实参
int tmp = m;
m = n;
n = tmp;
}
int main(){
int a = 1024, b = 9527;
cout << "a=" << a << ",b=" << b << endl;
exchange(a,b);
cout << "a=" << a << ",b=" << b << endl;
int m = 1, n = 2;
exchange(m,n);
cout << m << "," << n << endl;
return 0;
}
引用的应用
#include <iostream> //02ref.cpp
using namespace std;
int main(){
int a = 1024;
cout << &a << endl;
cout << a << endl;
int& r = a;//定义引用变量r 引用 a
cout << &r << endl;
cout << r << endl;
r = 9527;
cout << r << endl;
cout << a << endl;
a = 1212;
cout << a << endl;
cout << r << endl;
double d = 3.14;
double& rd = d;
return 0;
}
-
函数的返回值 需要确保在函数调用之后,返回的对象依然有效 能够返回全局变量、静态变量、动态内存对象引用参数的引用 不能返回局部变量的引用,编译警告;引用的对象的值不确定、行为不确定 不能返回局部变量的引用
#include <iostream> //03initref.cpp
using namespace std;
void func(int& ra){
cout << ra << endl;
ra = 1111;
}
double& getd(void){
double d = 6.666;
return d;//不能返回局部变量的引用
}
int main(){
//int& r;
int a = 10;
int& r1 = a,r2;//r1是引用 int&, r2是int
func(a);
cout << a << endl;
double& rd = getd();
cout << rd << endl;
return 0;
}
★引用与指针
|