Are static variables in a base class shared by all

2020-01-25 05:08发布

If I have something like

class Base {
    static int staticVar;
}

class DerivedA : public Base {}
class DerivedB : public Base {}

Will both DerivedA and DerivedB share the same staticVar or will they each get their own?

If I wanted them to each have their own, what would you recommend I do?

7条回答
Animai°情兽
2楼-- · 2020-01-25 06:05

There is only one staticVar in your case: Base::staticVar

When you declare a static variable in a class, the variable is declared for that class alone. In your case, DerivedA can't even see staticVar (since it's private, not protected or public), so it doesn't even know there is a staticVar variable in existence.

查看更多
登录 后发表回答