完整教程:C++语法 | static静态|单例模式

static 关键字

在此之前, 先了解一下 static 关键字

静态局部变量 vs 局部变量

在静态局部变量中,变量不会在函数调用结束后销毁,值会保留
变量在函数调用结束后依然存在。

所以每个函数访问的都是同一个 count 。但如果该函数是int count = 0; counter()将都是“函数已被调用1次”

#include <iostream>
  using namespace std;
  void counter() {
  // 静态局部变量 - 在函数调用之间保持值
  static int count = 0;
  count++;
  // 每次调用增加计数
  cout <<
  "函数已被调用 " << count <<
  " 次" << endl;
  }
  int main() {
  counter();
  // 输出: 函数已被调用 1 次
  counter();
  // 输出: 函数已被调用 2 次
  counter();
  // 输出: 函数已被调用 3 次
  return 0;
  }

.
.
.

静态全局变量 vs 全局变量

静态全局变量 - 只能在当前文件访问
而全局变量 是任何文件都可以访问的

#include <iostream>
  using namespace std;
  // 静态全局变量 - 只能在当前文件访问
  static int counter = 0;
  void increment() {
  counter++;
  cout <<
  "计数器值: " << counter << endl;
  }
  int main() {
  increment();
  // 输出: 计数器值: 1
  increment();
  // 输出: 计数器值: 2
  increment();
  // 输出: 计数器值: 3
  return 0;
  }

.
.
.
.

静态成员变量 vs 成员变量

基本上等同与静态局部变量 与 局部变量:)

#include <iostream>
  using namespace std;
  class Counter
  {
  public:
  // 静态成员变量声明
  static int count;
  Counter() {
  count++;
  // 每次创建对象时增加计数
  }
  };
  // 静态成员变量定义和初始化(必须在类外)
  int Counter::count = 0;
  int main() {
  cout <<
  "初始计数: " << Counter::count << endl;
  // 0
  Counter obj1;
  cout <<
  "创建obj1后: " << Counter::count << endl;
  // 1
  Counter obj2;
  cout <<
  "创建obj2后: " << Counter::count << endl;
  // 2
  }

.
.
.
.

静态成员函数

就是专门用来操作静态成员变量的,函数的返回值就是静态局部变量
静态局部变量的作用你懂吧?
只用打出一个商标,后面的都是用同一个商标,这就是单例模式最重要的一点

static Singleton* getInstance()
{
return &instance;
}

.
.
.
.

单例模式

这里只讨论线程安全下的懒汉模式

class Singleton
{
public:
static Singleton* getInstance() // 静态成员方法 #2
{
static Singleton instance;
// 静态局部变量 #3
return &instance;
//返回一个静态局部变量的地址 #4
}
private:
Singleton() { cout <<
"Singleton()" << endl;
} //私有的构造函数 #1
~Singleton() { cout <<
"~Singleton()" << endl;
}
Singleton(const Singleton&
) = delete;
Singleton&
operator=(const Singleton&
) = delete;
};
int main()
{
Singleton* p1 = Singleton::getInstance();
Singleton* p2 = Singleton::getInstance();
Singleton* p3 = Singleton::getInstance();
cout << p1 << endl;
cout << p2 << endl;
cout << p3 << endl;
return 0;
}
posted @ 2025-09-16 19:11  wzzkaifa  阅读(41)  评论(0)    收藏  举报