Why static variable needs to be explicitly defined?

前端 未结 5 1659
孤独总比滥情好
孤独总比滥情好 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:43

    Structure is not variable, but its instance is. Hence we can include same structure declaration in multiple modules but we cannot have same instance name defined globally in multiple modules.

    Static variable of structure is essentially a global variable. If we define it in structure declaration itself, we won't be able to use the structure declaration in multiple modules. Because that would result in having same global instance name (of static variable) defined in multiple modules causing linker error "Multiple definitions of same symbol"

提交回复
热议问题