当前位置:编程学习 > C/C++ >>

static成员理解

 

有时程序中有些数据需要持久保存,或者其他原因,需要调用全局的,但全局的对于开发来说,比较危险。这里介绍static,感觉很有用。

 

      对于static我是这样理解的:

 

类中的一般成员在生成对象的时候,每个成员都关联着对象。因此对象可以调用自己的成员,因此this指针也就有了意义,而对于static声明的成员,只关联于类,生成对象的时候不对该成员进行实例化,因此对象无法对此成员进行调用,this指针也就没意义了。

 

      除此之外,感觉static很有优势,可以替代全局的部分功能,同时还具有了封装属性。具体如下代码:

 

Test.h

 

 

#ifndef TEST_H 

#define TEST_H 

 

#include<iostream> 

using namespace std; 

 

class Test 

    public: 

        Test(); 

        void set(); 

        void print(); 

        virtual ~Test(); 

    protected: 

    private: 

        static int num;         //私有静态成员,具有封装性 

        //static int num = 0;   //声明时也不能定义。但const static int num=0;可以定义,例外。 

}; 

#endif // TEST_H 

 

#include "../include/Test.h" 

int Test::num = 0;      //静态成员初始化 

Test::Test() 

    //ctor 

   // this->num = 0;    //静态成员只能定义一次,不能在类初始化中定义 

void Test::set() 

    num ++; 

void Test::print() 

    cout << num << endl; 

 

Test::~Test() 

    //dtor 

 

#include <iostream> 

#include "./include/Test.h" 

using namespace std; 

 

int main() 

    Test t; 

    // t.num = 9;  //私有成员无法使用 

    t.set(); 

    t.print(); 

    return 0; 

 

 

望广大网友给予指导…

 

摘自Leeboy_Wang的专栏

补充:软件开发 , C语言 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,