可能重复:
解决链接器错误:未定义对静态类成员的引用
此声明:static unsigned NbCPassant;
仅在课堂外有效。如果我把它放在里面,(让它私有)这不会编译,错误:
undefined reference to `(anonymous namespace)::CPassant::NbCPassant'
我不明白为什么。这是代码:
#include <iostream>
#include <unistd.h>
#include <vector>
#include "SleepChronogram.h"
#include "nsUtil.h"
using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace nsUtil;
static unsigned CptThreads;
char * nsUtil::clrscr = "\033[2J"; // Clear screen
#define GOTOXY nsUtil::gotoxy
GOTOXY::gotoxy (int x, int y) : m_x (x), m_y (y) {}
ostream & nsUtil::operator << (ostream & os, const gotoxy & m)
{
return os << "\033[" << m.m_y << ';' << m.m_x << 'H';
}
#undef GOTOXY
namespace
{
void RendezVous ()
{
CptThreads--;
while(CptThreads)
{
condition_variable Cond;
mutex mut;
unique_lock<boost::mutex> lock(mut);
Cond.wait(lock);
}
}
class CPassant {
private:
static unsigned NbCPassant;
unsigned NbP;
unsigned TpsAvantRDV;
unsigned TpsApresRDV;
public:
CPassant (unsigned TpsAv, unsigned TpsAp)
:NbP(NbCPassant++) , TpsAvantRDV (TpsAv), TpsApresRDV (TpsAp) {}
void operator () ()
{
sleep(TpsAvantRDV);
RendezVous();
sleep(TpsApresRDV);
}
};
}
void nsUtil::SleepChronogram (unsigned Num,
unsigned & Col,
char Status,
unsigned Duree,
boost::mutex & ioMutex,
unsigned Decal /* = 10u */,
unsigned Periode /* = 1u */)
throw (std::ios_base::failure)
{
for (unsigned i = Duree; i--; )
{
{
lock_guard <mutex> Lock (ioMutex);
cout << gotoxy (Col++, Num + Decal) << Status << flush;
}
this_thread::sleep (seconds (Periode));
}
} // SleepChronogr()
int main (int argc, char ** argv)
{
if (argc != 1)
return 0;
int NbThreads = atoi(argv[1]);
if (NbThreads <1)
return 0;
vector <CPassant> VCPassant;
VCPassant.reserve(NbThreads);
for (int DelaiAv, DelaiAp, i (0) ; i < NbThreads; ++i)
{
cin >> DelaiAv >> DelaiAp;
VCPassant.push_back(CPassant(DelaiAv, DelaiAp));
}
return 0;
}