我有以下程序可以在我的机器上使用 GCC 7.5.0 成功编译,但是当我尝试该程序时 here该程序不起作用。
class Foo
{
friend void ::error() { }
};
int main()
{
return 0;
}
错误here说:
Compilation failed due to following error(s).
3 | friend void ::error() { }
| ^
我的问题是这里的问题是什么,我该如何解决。
最佳答案
问题是一个合格的 friend 声明不能是一个定义。在您的示例中,由于名称 error
是限定的(因为它具有 ::
),因此相应的友元声明不能是定义。
这似乎是 GCC 7.5.0 中的错误。例如,对于 gcc 7.5.0,程序 works但对于 gcc 8.4.0 及更高版本 doesn't work .
解决此问题的一种方法是删除 error
函数的主体 { }
,并通过添加分号 使其成为一个声明>;
如下图:
//forward declare function error()
void error();
class Foo
{
friend void ::error();//removed the body { } . This is now a declaration and not a definition
};
int main()
{
return 0;
}
//definition of function error
void error()
{
}
请注意,您还可以将函数 error()
的定义放在类 Foo
的定义之前,如 here 所示。 .
解决此问题的另一种方法是删除 ::
并使 error
成为 unqualified name,如 here 所示
关于c++ - 程序适用于 PC 上的 GCC 7.5,但不适用于在线编译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71005029/