【发布时间】:2021-09-02 18:08:40
【问题描述】:
我试图了解编译器如何处理此代码。这两个类方法都在定义之前引用了枚举,但只有一个会产生编译错误。我正在使用 GCC 9.2:
class Test {
public:
Test() {}
~Test(){}
//gcc seems to be happy with this...
int Foo()
{
TestState v = TestState::Value1;
if (v == TestState::Value1) {
return 0;
} else if (v == TestState::Value2) {
return 1;
}
}
// ... but it doesn't work when used as a parameter
int Bar(TestState v)
{
if (v == TestState::Value1) {
return 0;
} else if (v == TestState::Value2) {
return 1;
}
}
private:
enum class TestState:bool
{
Value1 = false,
Value2 = true
};
};
在这种情况下,函数 Foo 在 gcc 9.2 下编译得很好,但 Bar 没有:
enum.cpp:18:13: error: ‘TestState’ has not been declared
int Bar(TestState v)
^
enum.cpp: In member function ‘int Test::Bar(int)’:
enum.cpp:20:13: error: no match for ‘operator==’ (operand types are ‘int’ and ‘Test::TestState’)
if (v == TestState::Value1) {
^
enum.cpp:22:20: error: no match for ‘operator==’ (operand types are ‘int’ and ‘Test::TestState’)
} else if (v == TestState::Value2) {
为什么 gcc 在一个实例中似乎接受在定义之前使用枚举,而在另一个实例中不接受?我知道枚举应该在这些函数之前声明,但是为什么Foo编译没有错误?
【问题讨论】:
标签: c++11 enums compiler-errors