user3074166
user3074166

Reputation: 33

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

Upvotes: 1

Views: 2918

Answers (4)

doctorlove
doctorlove

Reputation: 19242

You do need include guards.

Edit

Assuming the edit to the question, which gives include guards actually uses armor as follows,

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

You then try to use armor as a variable name. Try

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

instead

End Edit

Also, class Knight needs a trailing semicolon.

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.

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254461

#define armor

Now you can't use the name armor in any source file that includes this header. 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. You might also consider #pragma once rather than a macro-based include guard, although that's not guaranteed to be portable.

Upvotes: 4

IInspectable
IInspectable

Reputation: 51415

In Knight.h the class definition is missing a ;:

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. void is not a legal symbol, and this triggers the error.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234715

Don't forget to close your Knight class declaration with a semicolon!

(Out of interest this is required in C++, not in Java).

Upvotes: 3

Related Questions