问题
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