加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c/c++ static关键字实例讲解

发布时间:2020-12-15 04:55:48 所属栏目:百科 来源:网络整理
导读:static关键字 1,static 成员变量 static 成员变量不随着对象的创建而开辟内存空间。也就是说,不管从哪个对象去看static成员变量,都是一样的。 2, static 成员方法 static 成员方法里不可以调用非static 成员方法。 非static 成员方法里可以调用static 成

static关键字

1,static 成员变量

static 成员变量不随着对象的创建而开辟内存空间。也就是说,不管从哪个对象去看static成员变量,都是一样的。

2, static 成员方法

static 成员方法里不可以调用非static 成员方法。

非static 成员方法里可以调用static 成员方法。

原因:非static 成员方法里是没有this指针的,所以在里面调用非static 成员方法时,无法传递this指针。static 成员方法不需要this指针。

重点:初始化static成员变量,要在类的外面。

#include

using namespace std;

class Test{

friend void fun(const Test &t);

public:

Test(int d = 0) : data(d){

count++;

}

~Test(){

count--;

}

private:

int data;

static int count;

};

void fun(const Test &t){

cout << t.data << endl;

cout << Test::count << endl;

}

//初始化static成员变量

int Test::count = 0;

int main(){

//int Test::count = 0;//编译不过,必须在外面初始化static成员变量

//Test::count = 0;//编译不过,必须在外面初始化static成员变量

Test t(10);

fun(t);

Test t1(11);

fun(t1);

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读