Why static variable needs to be explicitly defined?

前端 未结 5 1651
孤独总比滥情好
孤独总比滥情好 2020-11-27 21:07

In the class:

class foo
{
public:
    static int bar; //declaration of static data member
};

int foo::bar = 0; //definition of data member

W

5条回答
  •  北海茫月
    2020-11-27 21:41

    In early C++ it was allowed to define the static data members inside the class which certainly violate the idea that class is only a blueprint and does not set memory aside. This has been dropped now.

    Putting the definition of static member outside the class emphasize that memory is allocated only once for static data member (at compile time). Each object of that class doesn't have it own copy.

提交回复
热议问题