为什么此枚举不转换为int? [英] Why doesn't this enum convert to int?
问题描述
为什么以下代码无法在g ++(C ++ 14),MSVC(C ++ 14)或ARM(C ++ 03)下编译?
Why does the following code not compile under g++ (C++14), MSVC (C++14), or ARM (C++03)?
命名的Error实例调用整数构造函数,但匿名Error实例无法解析。
The named Error instance calls the integer constructor, but the anonymous Error instance does not resolve.
class Error
{
public:
Error(int err) : code_(err) {}
const int code_;
};
enum Value
{
value_1
};
int main()
{
// compiles
Error e(value_1);
// does not compile under G++, ARM, or MSVC
Error(value_1);
}
G ++下的示例错误:(花色链接)
Example error under G++: (Coliru link)
g ++ -std = c ++ 14 -O2 -Wall -pedantic -pthread main.cpp&& ./a.out
main.cpp: In function 'int main()':
main.cpp:19:18: error: no matching function for call to 'Error::Error()'
Error(value_1);
^
main.cpp:4:5: note: candidate: Error::Error(int)
Error(int err) : code_(err) {}
^~~~~
main.cpp:4:5: note: candidate expects 1 argument, 0 provided
main.cpp:1:7: note: candidate: constexpr Error::Error(const Error&)
class Error
^~~~~
main.cpp:1:7: note: candidate expects 1 argument, 0 provided
main.cpp:1:7: note: candidate: constexpr Error::Error(Error&&)
main.cpp:1:7: note: candidate expects 1 argument, 0 provided
推荐答案
这与最令人头疼的解析来自同一个地方-一条规则,即它可以是一个声明,它是是声明。
令人惊讶的是,您可以在变量声明中的标识符周围加上括号。
(我不知道为什么,但是我我猜想它简化了C的解析器。)
This comes from the same place as "The Most Vexing Parse" - the rule that if it can be a declaration, it is a declaration.
And surprisingly, you're allowed to put parentheses around the identifier in a variable declaration.
(I have no idea why, but I'm guessing that it simplified C's parser back in the day.)
以下是所有有效的 int $声明。 c $ c>变量:
The following are all valid declarations of int
variables:
int (foo);
int (bar) = 0;
int (baz)(3);
int (twaddle)(baz);
这篇关于为什么此枚举不转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!