From: http://blog.csdn.net/qq575787460/article/details/7880972
学Qt时,发现只要包含头文件QApplication或者QCoreapplication,就用使用qApp,指向一个当前实例。
查看源码发现qApp是个宏:
QApplication中:#define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
QCoreapplication中:#define qApp QCoreApplication::instance()
所以可以肯定的是QCoreApplication有个静态函数instance()返回指向自己的指针。
- static QCoreApplication *instance() { return self; }
- static QCoreApplication *self;
在QCoreapplication.cpp中有如下代码:
- void QCoreApplication::init()
- {
- ......
- QCoreApplication::self = this;
- ......
- }
QCoreapplication构造函数中又调用init()
- QCoreApplication::QCoreApplication(QCoreApplicationPrivate &p)
- : QObject(p, 0)
- {
- init();
- // note: it is the subclasses' job to call
- // QCoreApplicationPrivate::eventDispatcher->startingUp();
- }
所以就是:定义程序唯一的实例时,初始化self指向自身。qApp是一个宏,替换后为调用相应的instance()。
自己模仿的:
myApplication.h
- #ifndef MYAPPLICATION_H
- #define MYAPPLICATION_H
- #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
- #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;
main.cpp
- #include "myapplication.h"
- extern void print1();
- extern void print2();
- int main()
- {
- print1();
- print2();
- myApplication app("实例测试");
- print1();
- print2();
- app.printAppName();
- myApp->printAppName();
- return 0;
- }
- /*
- 测试函数,测试通过myApp输出唯一的实例名
- */
- #include "myapplication.h"
- #include <iostream>
- void print1()
- {
- if(myApp==0)
- std::cout<<"myApp没有实例化"<<std::endl;
- else
- myApp->printAppName();
- }
- /*
- 测试函数,测试通过myApp输出唯一的实例名
- */
- #include "myapplication.h"
- #include <iostream>
- void print2()
- {
- if(myApp==0)
- std::cout<<"myApp没有实例化"<<std::endl;
- else
- myApp->printAppName();
- }