C++ - Initialize and modify a static class member

2019-08-04 01:52发布

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

标签: c++ class static
4条回答
放荡不羁爱自由
2楼-- · 2019-08-04 02:27

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.

查看更多
不美不萌又怎样
3楼-- · 2019-08-04 02:28

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

namespace { 
/* ... */    

    unsigned CPassant::LastID = 0;

}; // anonym namespace
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-08-04 02:32

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.

查看更多
倾城 Initia
5楼-- · 2019-08-04 02:32

you have to do

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

查看更多
登录 后发表回答