【问题标题】:C++ Generating a Unique ID [duplicate]C ++生成唯一ID [重复]
【发布时间】:2017-10-22 18:22:10
【问题描述】:

我在为每个对象生成唯一 ID 时遇到问题。

我的对象是一个歌曲对象,具有可变艺术家、流派等。

所以在我的 song.h 文件中,我有

private:
   int m_ID;
   static unsigned int IDSeed;

在我的 song.cpp 文件中

Song::Song()
{
    static unsigned int IDSeed = 0;
    m_ID = IDSeed++;

}

Song::Song(constructor variables)
{

    m_ID = IDSeed++;

}

我现在遇到的主要错误是 "unresolved external symbol private static unsigned int Song::IDSeed"

【问题讨论】:

  • 如果您使用默认构造函数 (Song a; Song b; Song c;) 构造它们,那么您将所有 ID 设置为零。
  • so in my song.h file under private 我有 为什么你不只显示你的歌曲类声明?二、static unsigned int IDSeed;unsigned int IDSeed = 0;不同
  • 不能简单的使用对象的内存地址(reinterpret_cast<std::uintptr_t>(this))作为唯一ID吗?没有两个活着的对象会共享一个地址(尽管一个对象可能会重新使用过去的地址,现在已经死了,一个)。

标签: c++


【解决方案1】:

在我看来 IDSeedSong 对象中必须相同,因此,它必须声明为静态。因此,在您的 song.h 文件中,您必须有类似的内容:

class Song {
    int m_ID;
    static unsigned int IDSeed;
    static int helper_seed() { IDSeed++; return IDSeed;}
    (...)
};

现在,您需要初始化静态成员。所以,在 song.cpp 中:

unsigned int Song::IDSeed = 0;

现在,在Song 对象的每个构造函数上,您可以执行以下操作:

Song::Song()
{
    m_ID = helper_seed();    
}

Song::Song(constructor variables)
{
    m_ID = helper_seed();
}

【讨论】:

  • 我现在遇到了“static unsigned int Song::IDSeed = 0;”的问题我收到错误,此处可能未指定存储类
  • 非常感谢我让它工作了。我必须从 song.cpp 中的 IDSeed 中删除 static 关键字才能使其正常工作。
【解决方案2】:

你可以使用对象的内存地址—— reinterpret_cast<std::uintptr_t>(this) - 作为唯一 ID,只要该 ID 在所有当前活动的对象中必须是唯一的即可。

没有两个活着的对象会共享一个地址(尽管一个对象可能会重新使用过去的地址,现在已经死了,一个)。

【讨论】:

    【解决方案3】:

    在您的代码中,static unsigned int IDSeed; 什么都不做。 unsigned int IDSeed = 0; 是一个“通常”的类(实例)变量,每次你初始化你的类时它都会被设置为零。如果你想拥有持久的价值,你必须让这个变量成为静态的。此外,您可以从Song() 中删除static unsigned int IDSeed;

    【讨论】:

    • 好的,当我这样做时,我收到错误“具有类内初始化程序的成员必须是 const” "
    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多