C ++生成唯一ID

时间:2017-10-22 18:22:10

标签: c++

我无法为每个对象生成唯一ID。

我的对象是一个歌曲对象,巫婆有变量艺术家,流派等。

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

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {


            if (number(1, 9) == 1) // number is a function, not a variable
            {
                // Do Stuff
            }

        }

        static int number(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
    }
}

在我的 song.cpp 文件中

private:
   int m_ID;
   static unsigned int IDSeed;

我现在得到的主要错误是“未解析的外部符号private static unsigned int Song :: IDSeed”

3 个答案:

答案 0 :(得分:1)

在我看来,State Unverified IP Address IPASSIGNED Manage IPs SMTP Hostname smtp.mailgun.org Default SMTP Login postmaster@MYSUBDOMAIN API Base URL https://api.mailgun.net/v3/MYSUBDOMAIN Default Password MYPASSWORD SMTP credentials API Key MYKEY 对象IDSeed必须相同,因此必须将其声明为静态。因此,在 song.h 文件中,您必须具有以下内容:

Song

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

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

现在,在unsigned int Song::IDSeed = 0; 对象的每个构造函数上,您可以执行以下操作:

Song

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

在您的代码中,static unsigned int IDSeed;什么都不做。 unsigned int IDSeed = 0;是&#34; usuall&#34; class(instance)变量,每次初始化类时它都将设置为零。如果要拥有持久值,则必须将此变量设置为static。此外,您可以从static unsigned int IDSeed;

中删除Song()
相关问题