首先看什么是引用:
引用和取地址很像,容易混淆。单独出现&a就是对a这个变量取地址,如果是int &a,就是声明这是一个引用。
//引用
#include <iostream>
using namespace std;
int main()
{
//基础知识
int a = 1234; //ref alias 参数别名
int &ra = a; //引用(没有定义,是一种声明)int *p = &a;
//规则:
//1.声明的时候必须初始化,一经声明不能更改
//2.&符号前有数据类型,是引用,其他都是地址
cout << "a=" << a << endl;
cout << "ra=" << ra << endl;
cout << sizeof(a) << endl; //都是4个字节
cout << sizeof(ra) << endl;
cout << &a <<endl; //地址都是一样的
cout << &ra <<endl;
//*****************************************************
return 0;
}
好了,现在我们来看引用的妙处:
这里甚至还用了函数重载。看注释:
//正式开始 引用
//引用的精髓在于传参
//引用的本质就是对指针的包装(引用的本质是指针)
//C++对裸露的内存地址(指针)作了一次包装
#include <iostream>
using namespace std;
void Swap(int *a,int *b)//用指针传递参数:开辟两个指针空间实现交换
{
int t;
t = *a;
*a = *b;
*b = t;
}
void Swap(int &c,int &d) //这里的c和d是引用,代表只是声明关系,不需要开辟新的空间
{
int t;
t = c;
c = d;
d = t;
}
int main()
{
int a = 3; int b = 4;
cout << a << b << endl;
Swap(&a,&b); //传的是指针(或者说地址,所以会把地址暴露在外面)
cout << a << b << endl;
//********************************************************
int c = 5; int d = 6;
cout << c << d << endl;
Swap(c,d); //传的是引用
cout << c << d << endl;
return 0;
}
来看一下内联函数的优缺点
//内联函数的优缺点
#include <iostream>
#include <stdio.h>
using namespace std;
#define SQR(X) ((X)*(X))//宏函数
//优点:内嵌到目标代码,减少了函数的调用
//缺点:在预处理阶段完成了替换,有可能出现语意上的差错
//int sqr(int x)
//{
// return x*x;
//}
//普通函数 缺点:无法避免压栈和出栈的开销
inline int sqr(int x)
{
return x*x;
}
//内联函数,集中了宏函数和普通函数的优点
//内嵌到目标代码,减少了函数的调用,避免压栈和出栈的开销
//缺点:频繁调用增加了代码的空间,适合代码量小的函数体(5-10行)
int main()
{
int i,j = 0;
while(i<5)
{
printf("%d\n",SQR(i++)); //结果是错误的
}
printf("...........................\n");
while(j<5)
{
printf("%d\n",sqr(j++));
}
return 0;
}