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 对象中。

猜你喜欢

转载自www.cnblogs.com/CodeWorkerLiMing/p/11002492.html