//myApplication.cpp #include "myapplication.h" #include <iostream> using std::cout; using std::endl; myApplication::myApplication(string _appName):appName(_appName) { if(self!=0) return; else self=this; } void myApplication::printAppname() { cout<<appName<<endl; } myApplication* myApplication::self=0;
//myApplication.h #ifndef MYAPPLICATION_H_INCLUDED #define MYAPPLICATION_H_INCLUDED #include <string> using std::string; #define myApp myApplication::instance() class myApplication { public: myApplication(string _appname); static myApplication* instance() {return self;} void printAppname(); private: static myApplication *self; string appName; }; #endif // MYAPPLICATION_H_INCLUDED看到了myApplication* myApplication::self=0;这一行我就有点犯糊涂了。为什么要这样赋值呢?可不可以在类里面赋值呢?我试了试,答案是不可以的。查了一下C++规定了类的静态成员变量要在类外赋值。我有了疑问,为什么要这样规定呢?
原文地址:http://blog.csdn.net/cqu20093154/article/details/42707883