简体   繁体   English

预期在';'之前的主表达式错误 代币

[英]error expected primary-expression before ';' token

Hello i have problem with this code 您好,我对此代码有疑问

Armor.h 装甲

#ifdenf armor
#define armor
class Armor {

private:
    int m_weight;

public:
    Armor(int weight);

};
#endif

Knight.h 骑士

#ifndef knight
#define knight

#include "Armor.h"
class Knight {
private:
    Armor* m_armor;
    string m_name;
    int m_strength;

public:
    Knight(string name, int strength);

    void setArmor(Armor* armor);
};
#endif

Knight.cpp 骑士

#include "Knight.h"
void Knight::setArmor(Armor* armor){
    m_armor = armor; // error occurred

}

Error: error: expected primary-expression before ';' 错误:错误:“;”之前的预期主表达式 token 代币

thanks for help 感谢帮助

#define armor

Now you can't use the name armor in any source file that includes this header. 现在,您不能在任何包含此标头的源文件中使用armor名称。 The preprocessor will remove it. 预处理器将其删除。

m_armor = armor; // error occurred

Whoops! 哎呀! The preprocessor turns that into 预处理器将其转换为

m_armor = ;

I suggest using the convention of ALL_CAPS for macros, and not for anything else, so that they can't stomp over regular code. 我建议将ALL_CAPS的约定用于宏,而不要用于其他任何宏,这样它们就不会影响常规代码。 You might also consider #pragma once rather than a macro-based include guard, although that's not guaranteed to be portable. 您可能还会考虑#pragma once而不是基于宏的include防护,尽管不能保证可移植性。

Don't forget to close your Knight class declaration with a semicolon! 不要忘了用分号结束您的Knight职业宣言!

(Out of interest this is required in C++, not in Java). (出于兴趣,这在C ++中是必需的,而不是在Java中)。

You do need include guards. 您确实需要包括警卫。

Edit 编辑

Assuming the edit to the question, which gives include guards actually uses armor as follows, 假设对问题的编辑(包括后卫)实际上按如下方式使用armor

#ifdenf armor //<<--- ARE YOU POSTING THE ACTUAL CODE... try #ifndef
#define armor
//...
#endif

You then try to use armor as a variable name. 然后,您尝试使用armor作为变量名。 Try 尝试

#ifndef ARMOR_INCLUDED
#define ARMOR_INCLUDED
//...
#endif

instead 代替

End Edit 结束编辑

Also, class Knight needs a trailing semicolon. 另外, Knight需要一个尾随的分号。

class Knight {
private:
    Armor* m_armor;
    string m_name;
    int m_strength;

public:
    Knight(string name, int strength);

    void setArmor(Armor* armor);
}; //<----------

As a general rule, if you get a compile error about syntax on one line, which looks OK, work backwards to see if something earlier is causing it. 通常,如果在一行上出现有关语法的编译错误,看起来不错,请向后工作以查看是否有更早的原因导致此错误。

In Knight.h the class definition is missing a ; Knight.h ,类定义缺少; :

class Knight {
    ...
};

Without the ; 没有的; the following token is interpreted as a symbol. 以下标记被解释为符号。 In your code ( Knight.cpp ) it is the code immediately following the include directive. 在您的代码( Knight.cpp )中,它是包含指令之后的代码。 void is not a legal symbol, and this triggers the error. void不是合法的符号,这会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM