今天学习用单例模式,但是写好后编译过去,运行始终有报错。
Linking...
1>LINK : E:\workspace\waveform\Debug\waveform.exe not found or not built by the last incremental link; performing full link
1>linearscale.obj : error LNK2001: unresolved external symbol "private: static class LinearScale * LinearScale::_pInstance" (?_pInstance@LinearScale@@0PAV1@A)
1>E:\workspace\waveform\Debug\waveform.exe : fatal error LNK1120: 1 unresolved externals
1>Build log was saved at "file://e:\workspace\ag2eval\sw\primace\waveform\waveform\Debug\BuildLog.htm"
1>waveform - 2 error(s), 0 warning(s)
初时怀疑是vc下qt的工程组织问题,利用修改vproj工程文件排除这个原因后。
发现是低级的静态成员初始化问题
LinearScale::LinearScale(UNIT a, const int& timescale, const long& count)
{
_baseUnit = a;
_timescale = timescale;
_totallength = count;
_pInstance = NULL; //error is here _pInstance is static type. !!
qreal xx, yy;
for (int i=0; i< _totallength; ++i)
{
xx = 11 + i*21;
yy = 0;
QGraphicsItem *item = new Grid(Qt::red, xx, yy);
item->setPos(QPointF(i,1));
item->setParentItem(this);
}
//_pItem = new QGraphicsItem();
}
pInstance 静态成员的初始化改在构造函数之外,问题解决。
LinearScale* LinearScale::_pInstance = NULL;
重新温习一遍吧,还有就是类的static方法里不能用非static成员变量。这也是常识了,我又犯低级错误,最近手太生了可能。