我收到静态数据成员的多个声明的链接错误。我采取了所有必要的预防措施以避免多次包含头文件,但仍然出现错误。
//dummymessage.h
#ifndef DUMMY_MESSAGE
#define DUMMY_MESSAGE
#pragma once
#include "stdafx.h"
#include "string"
class CDummyMessage
{
private:
static int CDummyMessage::ObjCount1;
public:
CDummyMessage(void);
CDummyMessage(std::string content, int type);
~CDummyMessage(void);
private:
std::string m_Message_content;
int m_type;
};
int CDummyMessage::ObjCount1 = 0;
#endif
//dummymessage.cpp
#include "stdafx.h"
#include "iostream"
#include "DummyMessage.h"
using namespace dummy;
CDummyMessage::CDummyMessage(void)
{
std::cout<<"Constructor called. ID: "<<++CDummyMessage::ObjCount1<<std::endl;
}
CDummyMessage::~CDummyMessage(void)
{
std::cout<<"Destructor called. ID: "<<--CDummyMessage::ObjCount1<<std::endl;
}
CDummyMessage::CDummyMessage(std::string content, int type):
m_Message_content(content)
{
}
//main.cpp
#include "stdafx.h"
#include "windows.h"
#include "list"
#include "process.h"
#include "iostream"
#include "DummyMessage.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
for(auto i = 0;++i < 10000;){
CDummyMessage* l_pNewMsg = new CDummyMessage("Test message", i);
g_Message_queue.push_front(l_pNewMsg);
} return 0;
}
我收到此链接错误:-
Error 1 error LNK2005: "private: static int dummy::CDummyMessage::ObjCount1" (?ObjCount1@CDummyMessage@dummy@@0HA) already defined in DummyMessage.obj C:\Users\Veil\documents\visual studio 2012\Projects\SmartPointerExample\SmartPointerExample\SmartPointerExample.obj