gpt4 book ai didi

c++ - 在两个语句中创建引用变量

转载 作者:太空狗 更新时间:2023-10-29 23:32:45 25 4
gpt4 key购买 nike

int x;
int& foo = x;

// foo is now a reference to x so this sets x to 56
foo = 56;

如何将语句 int& foo = x; 拆分为两个语句?

通过拆分,我的意思是使用两个语句,如下例所示:

int y;
int* ptr = &y;

我可以将 int* ptr = &y 拆分为两个声明指针的语句。

int* ptr;
ptr = &y; //then assigning the pointer to point to y

如何对引用做类似的事情?我也在寻找关于为什么或为什么不的解释?

最佳答案

不,这是做不到的,只有少数情况下可以省略引用的初始化程序,来自草案 C++ 标准部分 8.5.3 [dcl.init .ref]:

The initializer can be omitted for a reference only in a parameter declaration (8.3.5), in the declaration of a function return type, in the declaration of a class member within its class definition (9.2), and where the extern specifier is explicitly used. [ Example:

int& r1; // error: initializer missing
extern int& r2; // OK

—end example ]

至于为什么我们发现以下关于为什么引用不可从 The Design and Evolution of C++ 重置的基本原理:

It is not possible to change what a reference refers to after initialization. That is once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. I had in the past been bitten by Algol68 references where r1=r2 can either assign through r1 to the object referred to or assign to a new reference value to r1 (re-binding r1) depending on the type of r2. I wanted to avoid such problems in C++.

关于c++ - 在两个语句中创建引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com