c++错误:预期 ‘=’, ‘,’, ‘;’, ‘ asm”或“__attribute__”之前,“秘密”

c++ error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘secret’

本文关键字:秘密 attribute 之前 错误 预期 c++ asm      更新时间:2023-10-16

我不明白这个错误位于哪里。我花了好几个小时想弄明白,但没成功。我的编译器突出显示类secret。

#ifndef ENEMIES_H
#define ENEMIES_H

class secret {
private:
int damage;
int accuracy;
int hlth;
public:
int attack(int x);
int health(int x);
};
#endif

你正在用C编译器编译它,而不是c++编译器。例子:

$ cc -c -o example.o example.c
example.c:5: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’
before ‘secret’
make: *** [example.o] Error 1
$ mv example.c example.cpp
$ cc -c -o example.o example.cpp
$

很可能您已经完成了上面示例所显示的—使用.c扩展名命名文件,而不是使用.cpp.C或GCC将使用的任何其他扩展名来确定您的文件是用c++编写的。如果您不想更改文件名,可以使用-x标志来解决此错误:

$ cc -x c++ -c -o example.o example.c
$

使用clang而不是GCC给出更好的错误消息,但结果相同:

$ clang -c -o example.o example.c
example.c:5:1: error: unknown type name 'class'
class secret {
^
example.c:5:13: error: expected ';' after top level declarator
class secret {
            ^
            ;
2 errors generated.
$ clang -x c++ -c -o example.o example.c
$

但更好的是:

$ clang++ -c -o example.o example.c
clang++: warning: treating 'c' input as 'c++' when in C++ mode, 
this behavior is deprecated
$

这是有效的-但确切地解释了你的问题

我认为这个问题是你的类文件后缀是*.c,而不是*.cpp,你改变后缀为*.cpp。祝你好运~

当在HEADERS .pro部分中有正确的.h条目但在SOURCES中跳过.cpp时,即使使用.cpp文件扩展名也可能发生错误。

通常当file.h被复制粘贴到源文件而不改变扩展名时,在这种情况下,'make'命令也会在makefile中创建(CC)条目而不是(CXX)来处理头文件