I have a project where there is a class item
in a header item.h
. I need to use the item
class in both my main.cpp
file and my player.h
header.
There are example files to explain my situation :
main.cpp
:
#include "player.h"
#include "item.h"
#include <vector>
std::vector<Item> items;
int main(){
Item i;
Player p;
p.move(10);
i.ID = 10;
return 0;
};
player.h
:
#include "item.h"
#include <vector>
class Player{
public:
std::vector<Item> inventory;
int x;
void move(int i){x += i};
};
item.h
:
#include <string>
class Item{
public:
int ID;
std::string name;
};
It may contain errors as I didn't compiled it, and just wrote it for you to understand my situation. In my real project, I get errors for redefinition of the Item class. I'm new to C++.
You need to do this in item.h
:
#ifndef SOME_WORD
#define SOME_WORD // the same as above
//item.h content
#endif
You can now import item.h
in all the files that you want.