2

编译如下:

void bar() { /* ... */ }

void foo()
{
    struct MyStruct
    {
        friend void bar();
    };
}

int main()
{
    //..
}

导致错误:

错误:没有事先声明的本地类中的友元声明“void bar()”

为什么名称查找失败?我该如何解决?

4

1 回答 1

2

即使您将事物加为好友,也无法访问其封闭范围之外的本地类,因为The name of a local class is local to its enclosing scope- §9.8/1。


但是,如果您只想让它编译,请明确告诉它在全局范围内查找...

friend void ::bar();

*由于某种原因,这在 VS 中修复了它,但在 GCC 中没有

§11.3/11(感谢 jrok)

如果友元声明出现在本地类 (9.8) 中并且指定的名称是非限定名称,则在不考虑最内层非类范围之外的范围的情况下查找先前声明。

于 2012-01-03T21:26:47.937 回答