简体   繁体   中英

Static unordered_map pointer initialitation in C++

I got this C++ code:

Client.h:

#include <unordered_map>

using namespace std;

class Client{
    static unordered_map<int, Client*>* clients;
public:
    static void initializeClients();
}

Client.cpp

#include "Client.h"
#include <unordered_map>

using namespace std;

 void Client::initializeClients(){
     clients = new unordered_map<int, Client*>();
}

But the linker gives me a LNK2001 unresolved external symbol for the unordered_map. I have no idea of what I am doing wrong, but it seems that I am missing something. I am using Visual Studio 2013.

Any idea? Thank you in advice!

you need to declare clients in your cpp file :

#include "Client.h"
#include <unordered_map>

using namespace std;
unordered_map* Client::clients;

 void Client::initializeClients(){
     clients = new unordered_map<int, Client*>();
}

explenation: header file only tells the linker what kinds of symbols some cpp file(s) has. declaring a variable in the header file does not makes this variable appear by it self. here you need to instantiate the static map pointer in the cpp file by declaring it , and make other files know about him by specifing it in the header file

summery : static member variables and global variables need to be declared also in some cpp file in order to get instantiated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM