c++ - 程序适用于 PC 上的 GCC 7.5,但不适用于在线编译器

标签 c++ c++11 gcc

我有以下程序可以在我的机器上使用 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/

相关文章:

c++ - 如何在 c++ 中对 double 或 float 的尾数和指数部分进行(快速)操作?

c++ - vector 的初始化

c++ - 将 'const QVariant' 作为 'this' 参数传递会丢弃限定符 [-fpermissive]

c - 警告 - 整数运算结果在 c 中超出范围

c++ - 使用指向类的指针访问成员变量

c++ _bstr_t 而不是使用字符串

c++ - 如何将参数从c++传递到linux shell

c++ - MSCV、构造函数、析构函数和 NRVO 行为

c - 无法找到 gcc 何时链接到 libc

gcc 中的编译标志用于调试 gdb 中的静态变量(在 AIX 操作系统中)