C++ 创建引用变量

2023-12-18 10:32:42
? ? ? ? C和C++使用 & 符号来 指示变量的地址。C++给 & 符号赋予了另一个含义,将其用来声明引用。例如,要将rodents作为rats变量的别名:
int rats;
int & rodents = rats;

rats:老鼠

rodents:啮齿动物。

第二行代码使啮齿动物成为了老鼠的别名。

? ? ? ? 其中,&不是地址运算符,而是类型标识符的一部分。就像声明中的char*指向char的指针一样,int &指的是指向int的引用。上述引用声明允许将rats和rodents互换——它们指向相同的值和内存单元。

#include <iostream>
using namespace std;
int main()
{
        int rats = 10;
        int & rodents = rats;

        cout << "rats = " << rats << endl;
        cout << "rodents = " << rodents << endl;
        rodents++;
        cout << "rats = " << rats << endl;
        cout << "rodents = " << rodents << endl;
        cout << "&rats = " << &rats << endl;
        cout << "&rodents = " << &rodents << endl;

        return 0;
}

? ? ? ? ?第一次接触引用可能会有些困惑,因为有些人很自然地想到了指针,但是它们之间还是有区别的。例如,可以创建指向rats的引用和指针:

int rats = 101;
int & rodents = rats;
int * prats = &rats;

? ? ? ? 表达式rodents和*prats都可以和rats互换,而表达式&rodents和prats都可以同&rats互换。从这点来看,引用很像指针的另一种用法(其中,*接触引用运算符被隐式理解)。但是实际上,引用还是不同于指针的。除了表示法不同外,还有其他的差别。例如,差别之一是,必须在声明引用时将其初始化,而不能像指针那样,先声明,再赋值:

int rat;
int & rodent;
rodent = rat;

上述代码是错误的,必须在声明引用变量时进行初始化。

? ? ? ? 引用更接近const指针,必须在创建时进行初始化,一旦与某个变量关联起来,就将一直效忠于它。

int & rodents = rats;

????????实际上是下述代码的伪装:

int * const pr = &rats;

? ? ? ? 其中,引用rodents扮演的角色与表达式*pr相同。

#include <iostream>
using namespace std;
int main()
{
        int rats = 101;
        int & rodents = rats;

        cout << "rats = " << rats << endl;
        cout << "rodents = " << rodents << endl;
        rodents++;
        cout << "rats = " << rats << endl;
        cout << "rodents = " << rodents << endl;
        cout << "&rats = " << &rats << endl;
        cout << "&rodents = " << &rodents << endl;

        int bunnies = 50;
        rodents = bunnies;
        cout << "bunnies = " << bunnies << endl;
        cout << "rodents = " << rodents << endl;
        cout << "rats = " << rats << endl;

        cout << "&bunnies = " << &bunnies << endl;
        cout << "&rodents = " << &rodents << endl;

        return 0;
}

? ? ? ? 最初,rodents引用的是rats,随后程序尝试把rodents作为bunnies的引用:

rodents = bunnies;

????????但是可以发现rats和rodents的值变成了50,同时rats和rodents的地址是相同的,而其地址和bunnies的地址不同。也就是说,这个代码的意思是把bunnies变量的值赋值给了rat变量。所以我们知道,可以通过初始化声明来设置引用,但是不能通过赋值来设置。

文章来源:https://blog.csdn.net/m0_73671341/article/details/132725787
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。