C ++-初始化和修改静态类成员 [英] C++ - Initialize and modify a static class member

查看:109
本文介绍了C ++-初始化和修改静态类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在不创建此类的对象的情况下初始化静态类的成员。
这是我的代码:

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;
}

谢谢

注意:我已经查看了这些答案,但是没有一个起作用:

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

推荐答案

在cpp文件中执行以下操作:

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.

这篇关于C ++-初始化和修改静态类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆