5

C++ 左值引用与一级指针 - 木三百川

 1 year ago
source link: https://www.cnblogs.com/young520/p/16714145.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++ 左值引用与一级指针

左值引用用于一级指针时,有以下几种用法:

//方式一:引用一级指针,常规用法int a = 5;int * pa = &a;int * &rpa = pa; //方式二:引用指向常量的一级指针,以下几种为等效表示int a = 5;const int * pa = &a;const int * &rpac = pa; //方式一int const * &rpac = pa; //方式二 //方式三:引用一级指针的常引用,引用自身为常量int a = 5;int * pa = &a;int * const &crpa = pa; //方式四:引用指向常量的一级指针,且引用自身为常量,以下几种为等效表示int a = 5;int * pa = &a;const int * const &crpac = pa; //方式一int const * const &crpac = pa; //方式二

Microsoft Visual Studio 中连续多个 const 会被编译器解释成一个,即 const const const const int *&const int *& 等效,除此之外,const int const *&Microsoft Visual Studio 中也与 const int *& 等效,而 int *& constQT minGW 中将会报错,在 Microsoft Visual Studio 中与 int *& 等效。

各类型引用可修改属性如下表所示:

引用类型 修改 *rp 修改 rp
int * &rp 可以 可以
const int * &rp 不可以 可以
int * const &rp 可以 不可以
const int * const &rp 不可以 不可以

若将变量的地址赋予引用(例如 rp=&x),各类型引用可接受的变量地址如下表所示:

引用类型 int变量地址 const int变量地址
int * &rp 不可以 不可以
const int * &rp 不可以 不可以
int * const &rp 声明时可以(将创建临时变量) 不可以
const int * const &rp 声明时可以(将创建临时变量) 声明时可以(将创建临时变量)

若将一级指针变量赋予引用(例如 rp=p),各类型引用可接受的一级指针变量如下表所示。若赋值时等号右边是函数返回的临时指针变量(属于右值),则只有当等号左边为 int * const & 以及 const int * const & 类型时不会报错,此时必会创建临时变量(与 const 左值引用性质一致)。

引用类型 int *变量 const int *变量 int * const变量 const int * const变量
int * &rp 可以 不可以 不可以 不可以
const int * &rp 不可以 可以 不可以 不可以
int * const &rp 声明时可以 不可以 声明时可以 不可以
const int * const &rp 声明时可以(将创建临时变量) 声明时可以 声明时可以(将创建临时变量) 声明时可以

若将引用变量赋予引用(例如 rp=rp2),各类型引用可接受的引用变量如下表所示。比较上下两表可知,左值引用类型变量被初始化完毕后,若要将其赋值给另一引用变量,赋值时的表现与所引用类型的变量相一致。

引用类型 int *&变量 const int *&变量 int * const&变量 const int * const&变量
int * &rp 可以 不可以 不可以 不可以
const int * &rp 不可以 可以 不可以 不可以
int * const &rp 声明时可以 不可以 声明时可以 不可以
const int * const &rp 声明时可以(将创建临时变量) 声明时可以 声明时可以(将创建临时变量) 声明时可以

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK