c++ - LNK2001 静态属性和方法错误(Qt、C++)

标签 c++ qt lnk2001

<分区>

我有一个类 EventType,它具有以下 header (仅相关行):

#include<string>
#include<unordered_set>
#include<iostream>

class EventType
{
public:
    static EventType* getByName(std::string name);

    static EventType* getByID(std::string id);

    static void setAllEventTypes(std::unordered_set<EventType*> events);
    //...

private:
    static std::unordered_set<EventType*> allEvents; //stores all events
    std::string name;
    //...
    std::string akaID;
};

来源:

EventType* EventType::getByName(std::string name) {
    foreach(EventType * event, EventType::allEvents) {
        if(event->name == name) {
             return event;
        }
    }
    std::cout << "Error: Event with name " << name << "could not be found.\n";
}

EventType* EventType::getByID(std::string id) {
    foreach(EventType * event, EventType::allEvents) {
        if(event->akaID == id) {
            return event;
        }
    }
    std::cout << "Error: Event with aka.ID " << id << "could not be found.\n";
}

void EventType::setAllEventTypes(std::unordered_set<EventType*> events) {
    EventType::allEvents = events;
}

现在我得到了 LNK2001-错误:

eventtype.obj : error LNK2001: unresolved external symbol ""private: static class std::unordered_set<class EventType *,struct std::hash<class EventType *>,struct std::equal_to<class EventType *>,class std::allocator<class EventType *> > EventType::allEvents" (?allEvents@EventType@@0V?$unordered_set@PEAVEventType@@U?$hash@PEAVEventType@@@std@@U?$equal_to@PEAVEventType@@@3@V?$allocator@PEAVEventType@@@3@@std@@A)".

即使我没有使用 EventType 类外部的任何静态方法,我也会收到此错误。为什么会这样? EventType 不应该能够链接到自身吗?

最佳答案

您声明了 allEvents 但没有定义它,您需要在源文件中进行定义:

std::unordered_set<EventType*> EventType::allEvents;

关于c++ - LNK2001 静态属性和方法错误(Qt、C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513551/

相关文章:

c++ - 更改 Qt 应用程序的当前路径

windows - 带有进度和传输速率/速度的 PyQt 复制文件夹

c++ - 运算符(operator)溢出功能调用未正确调用

c++ - Unresolved external 噩梦

c++ - 从 C 文件调用 C++ 函数会出现 "undefined reference"编译器错误

c++ - 为什么我不能有一个与成员类型同名的方法?

c++ - 更多C++多继承乐趣

c++ - 是否可以将对象实例移动到 QT 项目中不同代码点的不同线程?

c++ - 未解析的外部符号 "class"

c++ - 如何使回文代码不用担心 (userInput) 字间距