即使在我关闭应用程序并重新启动它后,如何保持我的 ID 被阻止?



所以我必须做一个 c++ 赋值,我有以下说明:

  • 添加私人部分:

    int id; //contains an unique number to identify this object;
    //this number may not be used again!
    

    要启用此功能,请执行以下操作:

  • 将静态私有变量添加到类中,以便您可以跟踪 到目前为止创建的对象数。

  • 添加一个静态公共函数来获取这个数字

注意:关闭并重新启动应用程序后,仍应阻止使用的 ID 号。

我真的不了解这项任务,也不确定如何实施。你能帮我这个吗?

我能够为你找到一些东西。如果您有任何问题,请在评论中告诉我。这是我的代码:

#include <ctime>
#include <fstream>
#include <iostream>
#include <limits>
#include <random>
#include <unordered_set>
const char * DATAFILE_NAME = "data.dat"; 
class Object
{
public:
using id_t = int;
private:
static constexpr id_t MAX_ID = std::numeric_limits<id_t>::max();
static id_t objs_created;
static std::unordered_set<id_t> used_ids;
id_t m_id;
// Inits static vars (essentially a load function)
static void static_init()
{
std::ifstream static_vars;
static_vars.open(DATAFILE_NAME);
if (static_vars.is_open())
{ // This program has been run before, so load it
id_t line;
// Read every line of file into used_ids (1 ID per line)
while(static_vars >> line)
{
used_ids.insert(line);
}
// Now, size of used_ids will be the number of objects created
objs_created = used_ids.size();
// Close file
static_vars.close();
}
else
{ // File doesn't exist or is corrupted
std::ofstream mkFile;
mkFile.open(DATAFILE_NAME); // Make the file
mkFile.close();
// Initialize static variables
// unordered_set does not need to be init'd
objs_created = 0;
}
}
public:
Object()
{
if (used_ids.empty())
{
Object::static_init();
}
id_t rand_num = 0;
std::default_random_engine rand_generator(std::time(nullptr));
// Possible range for random number [0, (max of unsigned long long)]
std::uniform_int_distribution<id_t> number_range(0, MAX_ID);
do  // Set a random number over and over again until it is not found in 'used_ids'
{
rand_num = number_range(rand_generator);
} while (used_ids.find(rand_num) != used_ids.end());
// Set m_id to the random number
m_id = rand_num;
// Update static vars
used_ids.insert(m_id);
objs_created++;
}
// Save function that you can call
static void save() const
{
std::ofstream saveData;
saveData.open(DATAFILE_NAME);
if (saveData.is_open())
{
// Save every id on its own line
for (const auto& id : used_ids)
{
saveData << id << std::endl;
}
saveData.close();
}
else
{
std::cerr << "Error! Failed to open datafile!" << std::endl;
exit(1);
}
}
id_t get_id() const { return m_id; }
};
// Init static variables (required for linker)
std::unordered_set<Object::id_t> Object::used_ids;
Object::id_t Object::objs_created = 0;

int main()
{ // Testing the class
Object obj[5];
for (int i = 0; i < 5; i++)
{
std::cout << obj[i].get_id() << std::endl;
}
Object::save();
}

最新更新