信号函数调用静态函数问题信号函数调用类static成员函数,成员函数调用static成员。C/C++ code#include ios
信号函数调用静态函数问题
信号函数调用类static成员函数,成员函数调用static成员。
C/C++ code#include <iostream>#include <map>using namespace std;typedef std::map<int,int> INTMAP;class CStTest{ public: CStTest(){}; ~CStTest(){}; public: static void put() { a=5; } static int *get() { return &a; } INTMAP *GetMap() { return &initmap; } public: static int a; static INTMAP initmap;};CStTest *g_pModule;
C/C++ code#include "stTest.h"#include <signal.h>void SigCapture(int sig){ int a = *(CStTest::get()); g_pModule->GetMap().clear(); }int main(){ signal(SIGHUP, SigCapture); signal(SIGINT, SigCapture); signal(SIGTERM, SigCapture); signal(SIGABRT, SigCapture); CStTest *pModule = new CStTest; g_pModule = pModule; int a=1; int b=2; pModule->initmap.insert(make_pair(a,b)); delete pModule;}
编译报
^[[A/tmp/ccUqABiC.o: In function `main':
stTest.cpp:(.text+0x14b): undefined reference to `CStTest::initmap'
/tmp/ccUqABiC.o: In function `CStTest::get()':
stTest.cpp:(.text._ZN7CStTest3getEv[CStTest::get()]+0x4): undefined reference to `CStTest::a'
/tmp/ccUqABiC.o: In function `CStTest::GetMap()':
stTest.cpp:(.text._ZN7CStTest6GetMapEv[CStTest::GetMap()]+0x10): undefined reference to `CStTest::initmap'
collect2: ld returned 1 exit status
[解决办法]类的 static 成员变量必须在类的定义之外定义一次
在 .cpp 文件中加上
INTMAP CStTest::initmap;
int CStTest::a;
就可以了。
[解决办法] 问题1 pModule->initmap.insert(make_pair(a,b));这样调用initmap不可以,initmap是静态的 只能是CStTest::initmap这样调用
问题2 g_pModule->GetMap().clear(); 这个也有问题 ,g_pModule->GetMap();返回的是map的指针,调用clear()函数 应该用解引用运算符 g_pModule->GetMap()->clear();
问题 3 就是2楼说的,静态成员需在类的外面定义一下
[解决办法]好像还有个问题 g_pModule = pModule 他们只想同一块内存,delete pModule之后也会把g_pModule这片内存也删除了,除非你知道这样做,不过还是注意点比较好