打算建一个类,每生成一个对象就自动获取一个唯一的ID。
main.cpp
#include "stdio.h"
#include "CNode.h" int main(int argc, char** argv) { CNode cNode1; CNode cNode2; CNode cNode3; printf("cNode1.ID = %d\n ", cNode1.ulID); printf("cNode2.ID = %d\n ", cNode2.ulID); printf("cNode3.ID = %d\n ", cNode3.ulID); }
CNode.h
#ifndef CNODE__
#define CNODE__ class CNode { public: CNode(); virtual ~CNode(); static unsigned int ulIDCreator; unsigned int ulID; }; unsigned int CNode::ulIDCreator = 0; #endif
CNode.cpp
#include "CNode.h"
CNode::CNode(){ ulID = ++ulIDCreator; } CNode::~CNode(){ }
*** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -osrc\CNode.o ..\src\CNode.cpp g++ -oArctic.exe src\Main.o src\CNode.o src\CNode.o: In function `ZN5CNodeC1Ev': E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:9: multiple definition of `CNode::CNode()' src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here src\CNode.o: In function `ZN5CNodeD1Ev': E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:13: multiple definition of `CNode::~CNode()' src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here src\CNode.o: In function `ZN5CNodeD0Ev': E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:13: multiple definition of `CNode::~CNode()' src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here src\CNode.o: In function `ZN5CNodeC2Ev': E:/EclipseWorkspace/Arctic/Debug/../src/CNode.cpp:9: multiple definition of `CNode::ulIDCreator' src\Main.o:E:/EclipseWorkspace/Arctic/Debug/../src/Main.cpp:13: first defined here collect2: ld returned 1 exit status Build error occurred, build is stopped Time consumed: 687 ms.很奇怪的问题!怀疑是在不同文件中编译再连接在一块有问题。
于是去掉了CNode.cpp,只剩CNode.h。结果问题消失,
#ifndef CNODE__
#define CNODE__ class CNode { public: CNode(){ulID = ++ulIDCreator;}; virtual ~CNode(){}; static unsigned int ulIDCreator; unsigned int ulID; }; unsigned int CNode::ulIDCreator = 0; #endifconsole:
cNode1.ID = 1
cNode2.ID = 2 cNode3.ID = 3