c++基础:37.单例模式

cpp 复制代码
#include <iostream>
class Demo
{
	public:
	Demo(const Demo&)=delete;
	static Demo& Get()
	{
		static Demo demo;
		return demo;
	}
	private:
	Demo(){}
};

写一个生成随机数的单例类

cpp 复制代码
//Random.h
#pragma once
#include <random>
class Random
{
public:
	Random(const Random&) = delete;
	static Random& GetInstance();
	int GetNumber(int min, int max);
private:
	Random(){}
};
cpp 复制代码
//Random.cpp
#include "Random.h"
Random& Random::GetInstance()
{
	static Random random;
	return random;
}
int Random::GetNumber(int min, int max)
{
	std::random_device rd;
	std::mt19937 gen(rd());
	//随机数范围
	std::uniform_int_distribution<>dis(min, max);
	return dis(gen);
}
cpp 复制代码
//demo.cpp
#include <iostream>
#include "Random.h"
int main()
{
	for (int i = 0; i < 10; i++)
	{
		int num = Random::GetInstance().GetNumber(1, 100);
		std::cout << num << std::endl;
	}
	
	std::cin.get();
}

这是常规方式,每次使用都需要调用GetInstance()函数。这里可以使用另一种方法。

c 复制代码
//Random.h
#pragma once
#include <random>
class Random
{
public:
	Random(const Random&) = delete;
	static Random& GetInstance();
	//获取随机数
	static int Number(int min, int max);
	
private:
	int GetNumber(int min, int max);
	Random(){}
};
cpp 复制代码
//Random.cpp
#include "Random.h"


Random& Random::GetInstance()
{
	static Random random;
	return random;
}
int Random::GetNumber(int min, int max)
{
	std::random_device rd;
	std::mt19937 gen(rd());
	//随机数范围
	std::uniform_int_distribution<>dis(min, max);
	return dis(gen);
}
 int Random::Number(int min, int max)
{
	 return GetInstance().GetNumber(min, max);
}
cpp 复制代码
#include <iostream>
#include "Random.h"
int main()
{
	for (int i = 0; i < 10; i++)
	{
		std::cout << Random::Number(1,100) << std::endl;
	}
	
	std::cin.get();
}
相关推荐
近津薪荼8 分钟前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先
xiaoye-duck9 分钟前
吃透 C++ STL list:从基础使用到特性对比,解锁链表容器高效用法
c++·算法·stl
_F_y14 分钟前
C++重点知识总结
java·jvm·c++
初願致夕霞1 小时前
Linux_进程
linux·c++
Thera7772 小时前
【Linux C++】彻底解决僵尸进程:waitpid(WNOHANG) 与 SA_NOCLDWAIT
linux·服务器·c++
Wei&Yan2 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
wregjru2 小时前
【QT】4.QWidget控件(2)
c++
浅念-2 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
小羊不会打字2 小时前
CANN 生态中的跨框架兼容桥梁:`onnx-adapter` 项目实现无缝模型迁移
c++·深度学习
Max_uuc3 小时前
【C++ 硬核】打破嵌入式 STL 禁忌:利用 std::pmr 在“栈”上运行 std::vector
开发语言·jvm·c++