c++引用对一些初次接触的朋友来说,理解稍微有点吃力,最起码对我来说,可能比较笨吧,好吧,笨鸟先飞。我也是看了一些资料,相关文章,最后结合自己敲的代码,理解出来的,进入正题。
1.定义引用
定义引用使用&符合,引用实际上是就是变量的别名,对变量的操作和引用的操作都是操作同一个东西。
比如 一个人,身份证上的名字叫 马化腾,外号 小马哥, 不管使用哪个称呼都指的是一个人,小马哥就可以理解为别名。
int c = 10;
int &d = c; //d是c的别名,定义引用的时候必须初始化。
2.实例
代码
// ConsoleApp1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<string>//引用的类库文件
#include<iostream>//引用的累计文件
using namespace std;//命名空间
void swap(int &a, int &b);
void swapNo(int a, int b);
int & valplus(int &a);
int _tmain(int argc, _TCHAR* argv[])
{
cout << "未使用引用效果,值一样,地址不一样" << endl;
int a = 10;
int b = a;
cout<<"变量值: a:" << a << "--b:" << b << endl;
cout<<"变量地址:a:" << &a << "--b:" << &b << endl;
cout << "---------------------------" << endl;
cout << "使用引用效果,值一样,地址一样" << endl;
int c = 10;
int &d = c; //d是c的别名
cout << "变量值: c:" << c<< "--d:" << d << endl;
cout << "变量地址:c:" << &c << "--d:" << &d << endl;
cout << "---------------------------" << endl;
cout << "未使用引用参数函数,交换前后值没有变化" << endl;
int m = 1,n = 2;
cout << "交换前: m:" << m << "--n:" << n << endl;
swapNo(m, n);
cout << "交换后: m:" << m << "--n:" << n << endl;
cout << "---------------------------" << endl;
cout << "使用引用参数函数,交换后值发生变化" << endl;
int x = 1, y = 2;
cout << "交换前: x:" << x << "--y:" << y << endl;
swap(x, y);
cout << "交换后: x:" << x << "--y:" << y << endl;
cout << "---------------------------" << endl;
cout << "函数引用返回值" << endl;
int num1 = 10;
int num2;
num2 = valplus(num1);
cout << num1 << " " << num2 << endl;
//cout << "-----------------"<<endl;
//cout << "请输入姓名,按任意键继续" << endl;
//string name="";
//cin >>name ;
//cout << name<<" Hello World"<<endl;
system("pause");
return 0;
}
void swapNo(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int & valplus(int &a)
{
a = a + 5;
return a;
}
最后要说明一点,关于函数返回值使用引用的好处就是不会在内存中产生副本,