C++ - Initialize and modify a static class member

2019-08-04 02:18发布

问题:

I don't know how to initalize a static class member without creating an object of this class. Here is my code:

namespace { 

    class CPassant : public thread
    {
        private:
            static unsigned LastID;

        public:
            CPassant (unsigned pDelaiArr = 0, unsigned pDelaiDep = 0)
            {
              (blabla)   
            }

            static void setLastID (unsigned Valeur)
            {
                LastID = Valeur; 
                    /* error : undefined reference to `(anonymous     
                        namespace)::CPassant::LastID' */

            } // setLastID ()

        }; // class CPassant

} // anonym namespace

int main ()
{
    CPassant::CPassant ().setLastID(0);
    //  doesn't work too:
// unsigned CPassant::LastID = 0;

    return 0;
}

Thanks

NB: I've already looked at those answers, but none of them worked:

stackoverflow.com/ initialize-a-static-member-an-array-in-c

stackoverflow.com/ how-to-initialize-a-static-member

回答1:

Do this in your cpp file:

unsigned CPassant::LastID = 0;

This is called defining the static class member, If you dont do this you will end up getting linker errors. You just declared the static member but did not define it.

Note that access specifiers do not matter here while defining the static member.



回答2:

You have declared, but not defined, the static member. You must define it. Here is one way:

namespace { 
/* ... */    

    unsigned CPassant::LastID = 0;

}; // anonym namespace


回答3:

you have to do

unsigned CPassant::LastID = 0; in the .cpp file..



回答4:

The problem with your initialization of LastID is that it's outside of the namespace you declared it. Put it in the same namespace and it will work.



标签: c++ class static