static成员变量

可以创建一个由同一个类的所有对象共享的成员变量。要创建这样的成员,只需将关键字 static 放在变量声明的前面,如下面的类所示:

复制代码
class StatDemo
{
    private:
        static int x;
        int y;
    public:
        void setx(int a) const { x = a; }
        void sety(int b) const { y = b; }
        int getx() { return x; }
        int gety() { return y; }
};
复制代码


接下来,在类之外放置一个单独的变量定义,

例如: int StatDemo::x;

在这个例子中,成员变量 x 将被 StatDemo 类的所有对象共享。当一个类对象将一个值放入 x 中时,它将出现在所有其他 StatDemo 对象中。

posted @   wdliming  阅读(449)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示