C++中级-引用

#include <iostream>

using namespace std;

//.引用的本质在C++内部实现的是一个指针常量,引用必须初始化;引用初始化后不能被改变(不能在引用别的东西);引用和原名使用同一内存空间,修改都是一起修改。


int main() 
{
    //引用:给变量起别名
    //语法:数据类型 &别名 = 原名
    int a = 10;
    int& b = a; //别名声明
    int& c = a;    
    cout << &b << endl; //&b = &a
    cout << &a << endl;
    cout << c << endl;
    b = 50;
    cout << a << endl;

    return 0;
}
引用定义
#include <iostream>
using namespace std;

//2.引用做函数参数


//2.1值传递
void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    cout << "inside a = " << a << endl;
    cout << "inside b = "<< b << endl;
}

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

//2.3引用传递
void swap3(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;

}


int main() {
    int a = 10;
    int b = 11;

    cout << "Before a  = " << a << endl;
    cout << "Before b  = " << b << endl;

    //swap2(&a, &b);
    //swap(a, b);
    //swap3(a, b);

    cout << "After a  = " << a << endl;
    cout << "After b  = " << b << endl;
    return 0;
}
引用做函数参数
#include <iostream>
using namespace std;

int &foo1() {
    int a = 11; // 局部变量,在栈区,函数结束便释放。
    return a;
}

int &foo2() {
    static int a = 22;//静态变量,在全局区,程序结束由系统释放。
    return a;
}
 


int main() {
    int& res = foo1(); // res为 foo1()返回值a的别名。
    cout << res << endl;//系统保留
    cout << res << endl;//自动释放

    int& res1 = foo2();
    cout << res1 << endl;
    cout << res1 << endl;

    foo2() = 100;
    cout << foo2() << endl;


    return 0;
}
引用做函数返回值

 数组引用:

void fun2() {
	int arr[3];
	int(&arr1)[3] = arr;

	
	arr[0] = 1;
	arr[1] = 10;
	arr[2] = 100;

	cout << arr[2] << endl;
	cout << arr1[2] << endl;

}

  

posted @ 2021-01-09 14:11  y0um  阅读(60)  评论(0编辑  收藏  举报

新人优惠服务器