有时,C++ 的隐私概念让我感到困惑 :-)
class Foo
{
struct Bar;
Bar* p;
public:
Bar* operator->() const
{
return p;
}
};
struct Foo::Bar
{
void baz()
{
std::cout << "inside baz\n";
}
};
int main()
{
Foo::Bar b; // error: 'struct Foo::Bar' is private within this context
Foo f;
f->baz(); // fine
}
既然Foo::Bar
是,private
我不能申报b
。但是我可以很好main
地调用方法。Foo::Bar
为什么这是允许的?这是意外还是设计使然?
哦,等等,它变得更好了:
Foo f;
auto x = f.operator->(); // :-)
x->baz();
即使我不允许命名类型Foo::Bar
,它也适用于auto
...
诺亚写道:
在类定义中定义的类型名称不能在没有限定的情况下在其类之外使用。
只是为了好玩,以下是从外部获取类型的方法:
#include <type_traits>
const Foo some_foo();
typedef typename std::remove_pointer<decltype( some_foo().operator->() )>::type Foo_Bar;