Can you declare multiple reference variables on the same line in C++?

大憨熊 提交于 2021-02-04 18:15:06

问题


I.e. are these legal statements:

int x = 1, y = z = 2;
int& a = x, b = c = y;

with the intended result that a is an alias for x, whileb and c are aliases for y?

I ask simply because I read here

Declaring a variable as a reference rather than a normal variable simply entails appending an ampersand to the type name

which lead me to hesitate whether it was legal to create multiple reference variables by placing & before the variable name.


回答1:


int x = 1, y = z = 2;--incorrect
int& a = x, b = c = y;--incorrect

The statements should be like this:

int x = 1, y =2,z = 2;
int&q=x,&b=y,&c=y;

All assignment and initialization statements in c++ should be of the following type:

lvalue=rvalue;

here lvalue must always be a variable to which a temporary value/another variable is assigned. rvalue can be another variable or an expression that evaluates to a temporary variable like (4+5).




回答2:


You need to append a & on the left of each reference (like you would need a * when you declare a pointer).



来源:https://stackoverflow.com/questions/16381088/can-you-declare-multiple-reference-variables-on-the-same-line-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!