I'm trying to declare a class that acts as enum. But if I include it more than once, I get several "duplicated symbol" errors.
This my ItemType.h
file
#ifndef DarkSnake_ItemType_h
#define DarkSnake_ItemType_h
#define COLOR_ITEM_1 0xffff00ff
#define COLOR_ITEM_2 0xffff03ff
#define COLOR_ITEM_3 0xffff06ff
class ItemType {
public:
static const ItemType NONE;
static const ItemType ITEM_1;
static const ItemType ITEM_2;
static const ItemType ITEM_3;
static ItemType values[];
static ItemType getItemTypeByColor(const int color) {
for (int i = 0; 3; i++) {
if (color == values[i].getItemColor()) {
return values[i];
}
}
return NONE;
}
bool operator ==(const ItemType &item) const;
bool operator !=(const ItemType &item) const;
int getItemColor() { return this->color; };
private:
const int color;
ItemType(const int _color) : color(_color) {}
};
bool ItemType::operator == (const ItemType &item) const {
return this->color == item.color;
}
bool ItemType::operator != (const ItemType &item) const {
return this->color != item.color;
}
#endif
And this my ItemType.cpp
:
#include "ItemType.h"
const ItemType ItemType::NONE = ItemType(0);
const ItemType ItemType::ITEM_1 = ItemType(COLOR_ITEM_1);
const ItemType ItemType::ITEM_2 = ItemType(COLOR_ITEM_2);
const ItemType ItemType::ITEM_3 = ItemType(COLOR_ITEM_3);
ItemType ItemType::values[] = {ItemType::ITEM_1, ItemType::ITEM_2, ItemType::ITEM_3};
In a first attempt I tried to put the C++ code into the header file, and I got the same errors. But now I don't know what am I doing wrong.
Can you help me, please?
Many thanks!
You can't define non-inline
functions outside a class in a header file.
To solve this, you have three possibilities:
operator==
and operator!=
inside the class definition.ItemType.cpp
.inline
.