“..."之前的预期主表达式,C++ 编译错误 [英] expected primary-expression before ‘...’, c++ compile error
问题描述
SO 上有很多帖子标题相似,但它们似乎是由各种语法错误触发的,我还没有看到一致的模式..
There are quite a few posts on SO with similar titles, but they seem to be triggered by various syntactic errors and I didn't see a consistent pattern yet..
using namespace std;
class A
{
public:
A(int a_) : a(a_) {}
int a;
};
int main()
{
A x{3};
A y{0};
if ((y=x).a)
cout << y.a << endl;
int i = 1;
if (int j = i)
cout << j << endl;
if ((A z = x).a) // error: expected primary-expression before ‘z’
cout << z.a << endl;
(int m = 1); // error: expected primary-expression before ‘int’
}
我是否错误地假设 A z = x
是一个赋值表达式,它应该与 z
具有相同的值?
Am I wrong to assume A z = x
is an assignment expression, which should have the same value as z
?
推荐答案
假设
A z = x
是赋值表达式,我错了吗
Am I wrong to assume
A z = x
is an assignment expression
是的,你错了.这里没有任务正在进行.此语句中的 =
表示初始化,而不是赋值.语句A z = x;
定义了变量z
,其中z
由x
构成.这里使用的是复制构造函数,而不是复制赋值.它是一个声明语句,而不是表达式语句.
Yes, you are wrong. There is no assignment going on here. The =
in this statement represents initialization, not assignment. The statement A z = x;
defines the variable z
, where z
is constructed from x
. The copy constructor is used here, not copy assignment. It is a declaration statement, not an expression statement.
您的困惑是相当普遍的,而且由于 if
语句中的条件可以是带有大括号或等号初始值设定项的单个非数组变量的声明而变得更糟.从语法上讲,带有等于"的声明初始化程序看起来很像赋值.正如您所发现的,一个很大的区别是您不能将声明视为子表达式.条件是声明或表达式,不是两者的混合.
Your confusion is reasonably common, and it is made worse by the fact that the condition in an if
statement can be a declaration of a single non-array variable with a brace-or-equals initializer. Syntactically, a declaration with an "equals" initializer can look a lot like an assignment. A big difference, as you discovered, is that you cannot treat the declaration as a sub-expression. The condition is either a declaration or an expression, not a mix of both.
好消息是 C++-17 添加了一个可选的init-statement 到 if
语句语法.因此,您似乎想要通过以下方式实现.
The good news is that C++-17 added an optional init-statement to the if
statement syntax. So what you appear to want would be achieved by the following.
if ( A z = x; z.a ) // Semicolon separates init-statement from condition
cout << z.a << endl;
// At the end of the `if` statement, `z` goes out of scope.
这篇关于“..."之前的预期主表达式,C++ 编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!