Studying initialization in C++: what does "error: expected '(' for function-style cast or type construction" means in this case?

huangapple go评论57阅读模式
英文:

Studying initialization in C++: what does "error: expected '(' for function-style cast or type construction" means in this case?

问题

我正在学习C++中的初始化。在这个概念验证中。我不理解编译器的建议。
(我已经知道在cin内声明变量不是一种容易和自然的方式(甚至可能不合法或不合适)。在这之前在外部声明它将更容易,也没有问题。但我提出这个问题只是为了更深入地理解发生了什么。试图更好地理解C++,尤其是初始化,这被认为不是一个简单的主题)。

#include <iostream>

int main()
{
    std::cin >> int input_value;
    return 0;
}

尝试编译时:

% g++ -Wall -o p44e1 p44e1.cc
p44e1.cc:5:18: error: expected '(' for function-style cast or type construction
        std::cin >> int input_value;
                    ~~~ ^
1 error generated.
英文:

I am studying initialization in C++. In this proof of concept. I don't understand compiler's advice.
(I already know that declaring a variable inside a cin is not the easy and natural (not even perhaps legal or even apropiate) way. Would be easy to just declare it outside before and no problem. But i asked the question just to understand more deeply what is going on. Trying to understand C++ in a better way and initialization in particular, which is known not to be a trivial subject).

#include &lt;iostream&gt;

int main ()
{
        std::cin &gt;&gt; int input_value;
        return 0;
}

when trying to compile:

 % g++ -Wall -o p44e1 p44e1.cc
p44e1.cc:5:18: error: expected &#39;(&#39; for function-style cast or type construction
        std::cin &gt;&gt; int input_value;
                    ~~~ ^
1 error generated.

答案1

得分: 6

一个函数体由零个或多个语句组成。

有几种不同的语句。在这里,我们只关心两种:

  • 声明语句,例如 int input_value;

  • 表达式语句。也就是 e;,其中 e 是一个表达式,意思是"用运算符连接的操作数,或者一个单独的操作数"。

    std::cin >> input_value; 就是一个表达式语句,其中 std::cininput_value 是操作数,>> 是运算符。

因此,std::cin >> int input_value; 是明显无效的。int input_value; 必须是一个独立的语句,但你试图将它嵌入到另一个(表达式)语句中。

英文:

A function body consists of zero or more statements.

There are several kinds of statements. We only care about two here:

  • A declaration statement, e.g. int input_value;

  • An expression statement. That is, e;. Where e is an expression, meaning "operands connected with operators, or an individual operand".

    std::cin &gt;&gt; input_value; would be an expression statement, where std::cin &gt;&gt; input_value is an expression (std::cin and input_value are operands, and &gt;&gt; is an operator).

So std::cin &gt;&gt; int input_value; is outright invalid. int input_value; must be a separate statement, but you tried to embed it into an other (expression) statement.

huangapple
  • 本文由 发表于 2023年4月4日 03:28:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定