设为首页 加入收藏

TOP

static成员理解
2014-11-24 00:04:18 来源: 作者: 【 】 浏览:11
Tags:static 成员 理解

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

对于static我是这样理解的:

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

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

Test.h

#ifndef TEST_H

#define TEST_H

#include

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

#include "./include/Test.h"

using namespace std;

int main()

{

Test t;

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

t.set();

t.print();

return 0;

}

望广大网友给予指导…

摘自Leeboy_Wang的专栏

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇关键字union的巧用,经典面试源代.. 下一篇在高警告级别干净利落的进行编译

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: