为什么编译器需要在已经类限定的成员函数定义的返回类型上使用类限定符

Why does the compiler require the class qualifier on the return type of an already class-qualified member function definition?

本文关键字:返回类型 定义 函数 成员 编译器 为什么      更新时间:2023-10-16

我有点不确定用什么措辞来描述这个问题,但举个例子:

Foo.h

namespace sample {
class Foo {
public:
enum Bar {
kValue1,
kValue2,
}
Bar SomeMethod(Bar some_value);
} 
}  // namespace sample

Foo.cc

namespace sample {
Bar Foo::SomeMethod(Bar some_value) { // compiler complains here
if (some_value == Bar::kValue1) {
return Bar::kValue2; // but not here
} else {
return Bar::kValue1;
}
}
}  // namespace sample

编译器抱怨定义中的返回类型说:

错误:未知类型名称"Bar">

为什么在SomeMethod的定义中赋予限定Foo::SomeMethod并没有将相同的限定扩展到Bar的返回类型,而是将限定扩展到该方法定义中Bar的所有其他用途?

Bar Foo::SomeMethod               (Bar some_value)
//^^^ Here is "outside" the class    ^^^ Here is "inside" the class

由于Bar是在类中定义的,因此需要使用Foo::前缀来访问它,除非您在类本身内部。

这是一个名称查找问题。通常,直到您进入参数列表或函数体:,您才能自动看到Foo的内部

namespace sample {
class Foo {
public:
enum Bar {
kValue1,
kValue2,
};
Bar SomeMethod(Bar some_value);
}; 
Foo::Bar Foo::SomeMethod(Bar some_value) {
if (some_value == Bar::kValue1) {
return Bar::kValue2;
} else {
return Bar::kValue1;
}
}
} //namespace sample
int main() {}