static关键字

一、 静态局部变量

使用static修饰的局部变量就是静态局部变量所在函数第一次调用时创建直到程序运行结束销毁所有对象共用这个一个静态局部变量

#include <iostream>

using namespace std;

class Test

{

public:

void test_static()

{

int a = 1;

static int b = 1; // 局部静态变量

cout << a++ << endl;

cout << b++ << endl << endl;

}

};

int main()

{

Test t1;

Test t2;

t1.test_static();

t2.test_static();

t1.test_static();

return 0;

}

二、静态成员变量

使用static关键字修饰成员变量就是静态成员变量

静态成员变量具有以下特点

1. const修饰的静态成员变量不能类内初始化必须类外初始化

2. 同一个所有对象共享一份静态成员变量

3. 静态成员变量可以直接通过类名调用无需关联任何对象因为静态变量程序执行创建程序结束销毁

 

#include <iostream>

using namespace std;

class Test

{

public:

int a = 1; // 成员变量

static int b; // 静态成员变量

};

int Test::b = 1; // 类外初始化

int main()

{

// 通过类名直接调用静态成员变量

cout << Test::b << " " << &Test::b << endl;

Test t1;

Test t2;

cout << t1.a++ << " " << &t1.a << endl;

cout << t2.a++ << " " << &t2.a << endl;

cout << t1.b++ << " " << &t1.b << endl;

cout << t2.b++ << " " << &t2.b << endl;

return 0;

}

三、静态成员函数

使用static修饰成员函数就是静态成员函数静态成员函数具有以下特点

1. 没有this指针因此不能调用非静态成员

2. 如果静态成员函数声明定义分离static需要写在声明即可

3. 除了可以使用对象调用还可以直接通过类名::调用更加推荐后者

 

#include <iostream>

using namespace std;

class Test

{

public:

int a = 1;

static int b;

static void func(); // 静态成员函数

};

int Test::b = 1;

void Test::func() // 类外定义

{

// cout << a << endl; 错误

cout << b << endl;

}

int main()

{

Test t;

t.func();

Test::func();

return 0;

}

 四、单例模式

模式设计(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。

单例 = 实例

实例 instance = 对象 object

单例模式可以全局创建保持一个

#include <iostream>

using namespace std;

/**

* @brief The Singleton class 单例模式的类

*/

class Singleton

{

private: // 构造函数私有化防止外部调用

Singleton(){}

Singleton(const Singleton&){}

public:

static Singleton& get_instance()

{

static Singleton instance;

return instance;

}

};

int main()

{

Singleton& s1 = Singleton::get_instance();

Singleton& s2 = Singleton::get_instance();

cout << &s1 << " " << &s2 << endl;

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值