提示:这个办法可以用在Qt C++程序和Qt QML的数据交换
首次初始化:DDocumentSets::getInstance()->setModel(oa_model);
以后任何class中都可以获得这个实例: DDocumentSet* oa_model = DDocumentSets::getInstance()->getModel();
并调用其方法: oa_model->xxxx();
header文件:
[cpp]view plaincopy
#ifndef DDOCUMENTSETS_H_
#define DDOCUMENTSETS_H_
#include "DDocumentSet.hpp"
class DDocumentSets {
private:
static DDocumentSets* _instance;
DDocumentSets();
DDocumentSet* model;
public:
static DDocumentSets* getInstance();
void setModel(DDocumentSet* oa_model);
DDocumentSet* getModel();
virtual ~DDocumentSets();
};
#endif /* DDOCUMENTSETS_H_ */
cpp文件:
[cpp]view plaincopy
#include "DDocumentSets.h"
DDocumentSets* DDocumentSets::_instance; //Jiang
DDocumentSets* DDocumentSets::getInstance() {
if (_instance == 0) {
_instance = new DDocumentSets();
}
return _instance;
}
void DDocumentSets::setModel(DDocumentSet* model) {
this->model = model;
}
DDocumentSet* DDocumentSets::getModel() {
return model;
}
DDocumentSets::DDocumentSets() {
}
DDocumentSets::~DDocumentSets() {
}
参考:
http://stackoverflow.com/questions/8612206/linker-error-when-using-static-members
在C++程序中,need to define the static variable in cpp file and not in header file.
在Qt程序中,需要在cpp和header文件中都定义相同名字的static变量。否则编译出错:
undefined reference to xxxx(static 变量)
--转自