C++ vector issue - 'LNK2001: unresolved external symbol private: static…'

前端 未结 3 1059
眼角桃花
眼角桃花 2021-02-05 09:45

Before anyone calls me out for not looking at pre-existing questions, I have looked and realise that it is to do with declaration, but I still can\'t get it to work (might be so

3条回答
  •  你的背包
    2021-02-05 10:18

    Oli and Constantinius have answered your actual question, but I would recommend changing the class. As it stands it has only static members, so you can never create an object of this class. While this is legal C++, it is not in the spirit of C++ (Although there are other languages that do embrace this usage, such as C#)

    All static members imply that you are trying for some kind of singleton, but there are more standard ways of enforcing the singleton-ness of a class.

    Having said that - I advocate never building singleton-ness into a class. Rather write the class as a normal class, and provide a singleton wrapper. This also has the neat side effect of preventing the notorious static initialization order fiasco that your current code is liable to bump into.

    So, something like (excluding the includes for brevity):

    Manager.h

    class Manager {
        vector airports;
        vector flights;
    public:
        Manager();
        void loadAirports();
        void loadFlights();
        Airport getAirport(string code);
        vector split(const string &s, vector &elems);
    };
    
    Manager& GetManager();
    

    Manager.cpp

    Manager::Manager()
    {
        loadAirports();
        loadFlights();
    }
    
    Manager& GetManager()
    {
        static Manager manager;
        return manager;
    }
    

提交回复
热议问题