【问题标题】:LNK2001 Error with static attributes and methods (Qt, C++) [duplicate]LNK2001静态属性和方法错误(Qt,C++)[重复]
【发布时间】:2017-11-27 14:41:28
【问题描述】:

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

#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-error:

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不应该能够链接到自己吗?

【问题讨论】:

    标签: c++ qt lnk2001


    【解决方案1】:

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

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

    【讨论】:

    • 这解决了它。我仍然想知道为什么,因为我是 C++ 和非静态成员的新手,在 .h 文件中声明它们总是足够的。谢谢!
    猜你喜欢
    • 2014-02-18
    • 2023-03-15
    • 2013-03-28
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多