C++和 Xcode 中出现重复符号错误

Duplicate symbol error in C++ and Xcode

本文关键字:符号 错误 Xcode C++      更新时间:2023-10-16

>我正在尝试声明一个充当枚举的类。但是,如果我多次包含它,则会出现几个"重复符号"错误。

这是我ItemType.h文件

#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

这是我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};

在第一次尝试中,我尝试将C++代码放入头文件中,但遇到了相同的错误。但现在我不知道我做错了什么。

你能帮帮我吗?

非常感谢!

不能

在头文件中定义类外部的非inline函数。

要解决此问题,您有三种可能性:

  1. 在类定义中移动operator==operator!=的定义。
  2. 将定义移动到 ItemType.cpp
  3. 声明函数inline
相关文章: