cpp:关于对`(匿名命名空间):: CPassant :: NbCPassant'的未定义引用的解释

时间:2012-12-03 13:45:56

标签: c++

  

可能重复:
  Resolving a linker error: undefined reference to static class members

此声明: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;
}

1 个答案:

答案 0 :(得分:1)

您只是在代码中声明 NbCPassant,您还需要定义

class CPassant { 
private:
    // Declare the variable
    static unsigned NbCPassant;
    ...
};

// Define the variable
unsigned CPassant::NbCPassant;