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();
}