静态成员变量,静态成员函数

静态成员变量

下例中a b 是普通成员变量,c为静态成员变量

class Test
{
private:
        /* data */
public:
        Test(int a,int b);
        ~Test();
        int a;
        int b;
        static int c;
};

Test::Test(int a,int b)
{
        this->a = a;
        this->b = b;
}

Test::~Test()
{
}

static 成员属于类,不属于具体的对象,所有的对象使用的都是同一个static c

静态成员变量的初始化,也在要类的外部进行,没有初始化过的静态成员变量不能使用,可以不赋值但必须初始化

本例中应该这样:

int Test::c = 0;

我们试着用不同的对象对这个静态成员变量改变

可以用

类::静态成员变量

对象.静态成员变量

这两种方式访问

class Test
{
private:
        /* data */
public:
        Test(int a = 0,int b = 0);
        ~Test();
        int a;
        int b;
        static int c;   //静态成员变量
};

Test::Test(int a,int b)
{
        this->a = a;
        this->b = b;
}

Test::~Test()
{
}

//初始化静态成员变量
int Test::c = 0;

int main(int argc, char const *argv[])
{
        Test test1,test2;
        cout<<Test::c<<endl;           
        test1.c++;
        cout<<test1.c<<endl;       
        test2.c++;
        cout<<test2.c<<endl;
}

输出结果

0
1
2

静态成员函数

普通成员函数可以访问所有成员(包括静态成员变量)

静态成员函数只能访问静态成员变量

class Test
{
private:
        /* data */
public:
        Test(int a = 0,int b = 0);
        ~Test();
        static int Add();       //静态成员函数
        int a;
        int b;
        static int c;   //静态成员变量
};

Test::Test(int a,int b)
{
        this->a = a;
        this->b = b;
}

Test::~Test()
{
}

//定义静态成员函数
int Test::Add()
{
        c++;
        cout<<c<<endl;
}

//初始化静态成员变量
int Test::c = 0;

int main(int argc, char const *argv[])
{
        Test test1,test2;
        test1.c++;
        cout<<test1.c<<endl;
        test2.c++;
        cout<<test2.c<<endl;
        Test::Add();
     test2.Add(); }

声明加static 定义不加 static

静态成员函数和静态成员变量一样,可以通过类调用 也可以通过对象调用

原文地址:https://www.cnblogs.com/qifeng1024/p/12658152.html