英文:
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 <iostream>
int main ()
{
std::cin >> int input_value;
return 0;
}
when trying to compile:
% 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.
答案1
得分: 6
一个函数体由零个或多个语句组成。
有几种不同的语句。在这里,我们只关心两种:
-
声明语句,例如
int input_value;
-
表达式语句。也就是
e;
,其中e
是一个表达式,意思是"用运算符连接的操作数,或者一个单独的操作数"。std::cin >> input_value;
就是一个表达式语句,其中std::cin
和input_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;
. Wheree
is an expression, meaning "operands connected with operators, or an individual operand".std::cin >> input_value;
would be an expression statement, wherestd::cin >> input_value
is an expression (std::cin
andinput_value
are operands, and>>
is an operator).
So std::cin >> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论