黑马程序员匠心之作-引用

1、引用的含义与注意事项

#include <iostream>
using namespace std;
#include<string>
#include<ctime>
int main()
{
    int  a = 10;//a指向的内存值为10
    int& b = a;//引用的定义,b与a指向同一个内存;
    cout << &a << "&b: " << &b << endl;
    int c = 20;//c指向的内存值为20;
        b = c;//c指向的内存值赋值给b指向的内存值;
        cout << " a:" << a << " b: " << b << " C: " << c << endl;
    //引用注意事项:
    //1,引用必须初始化;2,引用一旦初始化就不能改变;

    system("pause");
    return 0;
} 

2、引用函数参数传递

和指针传递相同可以修改实参,优点:形式上更简单。

#include <iostream>
#include<string>
#include<ctime>
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;
}
int main()
{
    int  a = 10;//a指向的内存值为10
    int b = 20;
    swap01(&a, &b);
    cout << "指针传递a:" << a << "指针传递b:" << b;
    swap02(a, b);
    cout << "引用传递a:" << a << "引用传递b:" << b;
    system("pause");
    return 0;
}

3、引用做函数返回值的注意事项:不能返回局部变量的引用

#include <iostream>
#include<string>
#include<ctime>
using namespace std;
int& test01()
{
    int a = 10;
    return a;//不能返回局部变量的引用;
}
int& test02()
{
    static int a = 10;//static关键字,a变为静态常量;
    return a;
}
int main()
{
    int& ref1 = test01();
    cout << ref1 << endl;//正常打印,编译器做一次数值保留;
    cout << ref1 << endl;//ref指向的内存数据被释放,a不再为10
    int& ref2 = test02();
    cout << ref2 << endl;//正常打印
    cout << ref2<< endl;//正常打印
    system("pause");
    return 0;
} 

4、引用的本质:指针常量

 5、防止引用作为函数参数传递时改变实参值:

函数传参时使用const修饰形参;则形参在函数内部不允许改变;

猜你喜欢

转载自blog.csdn.net/yyyllla/article/details/109328262
今日推荐