一、
#include<iostream>
#include<assert.h>
using namespace std;
//引用返回
// 1、减少拷贝
// 调用者可以修改返回对象
//int& count()
//{
// static int n = 0;
// n++;
// return n;
//}
//#define N 10
//typedef struct Array
//{
// int a[N];
// int size;
//}AY;
//int& postat(AY& ay, int i)
//{
// assert(i < N);
// return ay.a[i];
//}
//int main()
//{
// //int ret = count();
// AY ay;
// for (int i = 0; i < N;++i)
// {
// postat(ay, i) = i * 10;
// }
// for (int i = 0; i < N; ++i) {
// cout << postat(ay, i) << " ";
// }
// cout << endl;
// return 0;
//}
//
int& add(int a, int b)
{
int c = a + b;
return c;
}
int main()
{
int& ret = add(1, 2);
//add(3, 4);
cout << "add(1,2) is :" << ret << endl;
cout << "add(1,2) is :" << ret << endl;
return 0;
}
结论:如果函数返回时,出了函数作用域,如果返回对象(静态、全局、上一层栈帧、malloc的等等)还在(还没给系统),则可以使用引用返回,如果已经还给系统了,则必须使用传参返回。 如果使用引用返回,结果是未定义。
二、
//指针和引用,赋值/初始化 权限可以缩小,保持,但不能放大
//权限放大
/*const int c = 2;
int& d = c;
const int* p1 = NULL;
int* p2 = p1;*/
//例子
const int m = 1;
int n = m;
//权限保持
const int c = 2;
const int& d = c;
const int* p1 = NULL;
const int* p2 = p1;
//权限缩小
int x = 1;
const int& p4 = p3;
int* p3 = NULL;
const int* p4 = p3;
int conut()
{
int n = 0;
n++;
return n;
}
int main()
{
int ret = conut();//拷贝
int& ret = conut();//出错
const int& ret = conut();//因为返回不是n,而是临时变量不可修改,
int i = 10;
cout << (double)i << endl;//隐式转换
double dd = i;//显式转换,先产生临时变量(double类型),再给dd
double& rd = i;//临时变量具有常性,故出错
const double& rd = i;
return 0;
}