C++:引用类型(int &)

引用类型

给变量起别名
数据类型 &别名 = 原名

#include 
using namespace std;

int main(){

    int a = 10;
    int& b = a;
    cout << b << endl;

    system("pause");
    return 0;

}

注意:

  1. 引用要初始化
  2. 引用初始化后就不可以更改
    与&p取地址不同,不要混淆。
#include 
using namespace std;


int main(){

    int a = 10;
    int& b = a;

    int c = 20;
	//初始化后不能更改
    int &b = c; //错误 因为已经初始化过了
    cout << c << endl;

    system("pause");
    return 0;

}

在这里插入图片描述

引用做函数参数

函数传参时,可以利用引用让形参修饰实参。可以简化指针修改实参。

#include 
using namespace std;
//值传递
void swap01(int a,int b) {
    int temp = a;
    a = b;
    b = temp;
}

//地址传递
void swap02(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

//引用传递
void swap03(int& a, int& b) { //等于就是起别名修改
    int temp = a;
    a = b;
    b = temp;
}

int main(){

    int a = 10;
    int b = 20;

    system("pause");
    return 0;

}

引用作为函数返回值

  1. 不要返回局部变量的引用
  2. 函数的调用可以作为左值
#include 
using namespace std;

//不要返回局部变量引用
//int& test01() {
//  int a = 10;//局部变量存放在四区中的栈区
//  return a;
//}

int& test02() {
    static int a = 10;
    return a; 
}
int main(){

    int& ref2 = test02();
    test02() = 1000;
    //如果返回值是引用,这个函数调用可以作为左值。
    cout << "ref2: " << ref2 << endl;
    cout << "ref2: " << ref2 << endl;
    cout << "ref2: " << ref2 << endl;

    system("pause");
    return 0;

}

你可能感兴趣的:(C++,c++,经验分享)