请帮助我理解为什么类成员函数可以返回私有嵌套类对象,以及为什么可以在该私有嵌套类上调用成员函数,例如:
class Y
{
class X
{
public:
void f() { cout << "Hello World" << endl; }
};
public:
X g() { return X(); }
};
void h()
{
Y::X x; // Error, as expected: class Y::X is private.
x.f(); // Error.
Y y; // OK.
y.g().f(); // OK. But why???
}
Run Code Online (Sandbox Code Playgroud)
我使用GCC和Visual C++进行了测试,最后一行编译在两者上.我似乎无法在C++标准中找到任何可以使其有效的内容.任何想法为何有效?
编辑:
另一个观察:
void i()
{
Y y;
Y::X x2 = y.g(); // Error: class Y::X is private
x2.f(); // Error
auto x3 = y.g(); // …Run Code Online (Sandbox Code Playgroud) 以下代码是否符合(任何)C++ ISO标准?
#include <functional>
auto a() {
struct Foo {
};
return []() {return Foo{}; };
}
int main()
{
auto l = a()();
decltype(l) ll;
//Foo f; //error: unknown type name 'Foo'
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器(Visual Studio 2015,最新的Clang和最新的GCC)接受了这一点,但是decltype应该让我访问Foo似乎很奇怪.
c++ ×2