使用可选的'struct'关键字时的g ++警告

Ade*_*que 10 c++ struct namespaces g++ compiler-warnings

如果我写这个程序:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

并编译它:

g++ main.cxx -Wall -Wextra
Run Code Online (Sandbox Code Playgroud)

它给了我这个警告:

main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
Run Code Online (Sandbox Code Playgroud)

但是,如果我在struct关键字后面取出new关键字:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

并以相同的方式编译它,g ++输出没有警告.如果我使用struct关键字,为什么g ++会输出警告?

Tho*_*ews 5

在C++中,struct关键字定义了一个类型,新类型不再需要struct关键字.这是C和C++之间的许多差异之一.

  • 这解释了为什么后面的代码有效,但不是为什么第一个代码产生了警告. (5认同)