当所有逗号运算符不作为逗号运算符? [英] When all does comma operator not act as a comma operator?
问题描述
如果您看到此代码,
class A{
public:
A(int a):var(a){}
int var;
};
int f(A obj) {
return obj.var;
}
int main() {
//std::cout<<f(23); // output: 23
std::cout<<f(23, 23); // error: too many arguments to function 'int f(A)'
return 0;
}
f(23,23)
不编译,因为逗号作为分隔符而不是逗号运算符。
f(23, 23)
does not compile because the comma acts as a separator here and not as a comma operator.
所有逗号不作为逗号运算符?
Where all does a comma not work as a comma operator? Or the other way around?
推荐答案
从语法的角度看,函数调用的参数形成一个可选的表达式列表在括号中。一个表达式列表由一个或多个赋值表达式组成,以逗号分隔。逗号只能表示期望使用表达式的逗号运算符。
From a grammatical point of view, the parameters of a function call form an optional expression-list inside parentheses. An expression-list consists of one or more assignment-expression separated by a comma token. A comma can only signify a comma operator where an expression is expected.
逗号运算符会生成 ,,
和赋值语句一个逗号运算符本身不是一个 assignment-expression ,因此不能出现在 expression-list 中,除非它是一个
The comma operator makes an expression out of an expression, a ,
and an assignment-expression, but an expression involving a comma operator is not itself an assignment-expression so can't appear in an expression-list except where it's a constituent of something that is an assignment-expression.
例如,您可以使用括号中的任何表达式(包括使用逗号运算符的表达式) > primary-expression ,这是一个赋值语句,因此在表达式列表中有效。
For example, you can surround any expression (including one using the comma operator) inside parentheses to from a primary-expression which is an assignment-expression and hence valid in an expression-list.
Eg
postfix-expression 其中 expression-list / em>每个都是标识符。
postfix-expression where the expression-list consists of two assignment-expression each of which is an identifier.
f( a, b );
postfix-expression 其中 expression-list 由一个赋值表达式组成,它是一个使用逗号运算符的括号表达式的 primary-expression 。
postfix-expression where the expression-list consists of a single assignment-expression which is a primary-expression which is a parenthesized expression using the comma operator.
f( (a, b) );
这篇关于当所有逗号运算符不作为逗号运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!