一、 静态局部变量
使用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;
}