创建一个可以访问 class 实例的唯一 ID 的运算符

Creating an operator that can access the unique ID of an instance of class

我想为 class 的每个实例创建一个无法修改的唯一 ID。 然后我想创建一个运算符 == 使得 p1==p2 returns true 如果 p1 和 p2 具有相同的 id,即是相同的元素。 我打算这样做的方式是:

parent.hpp

class parent{
    public:
        ...
        int parent::GetUid() const;

    private:
        static int newUID;
        const int uid;

}

parent.cpp

bool operator ==(const parent p1, const parent p2)
{
    return (p1.GetUid()== p2.GetUid());
}

parent::parent()
:uid(newUID++){}


int parent::newUID=0;

int parent::GetUid() const
    {
        return uid;
    }

但是尽管我初始化 newUID,但我收到以下错误:

error c2789 an object of const-qualified type must be initialized

编辑:上述错误已解决,是我输入错误造成的。

现在,当我尝试使用运算符时,出现以下错误:

error C2676: binary '==' : 'parent' does not define this operator or a conversion to a type acceptable to the predefined operator

当我执行以下操作时出现此错误:

parent p1;
parent p2;
...
if(p1==p2){
    t=0;
}

为什么不直接使用每个家长的地址?

bool operator == (const parent &p1, const parent &p2)
{
    return &p1 == &p2;
}

parent::parent() :uid(newUID++){}至少应该能编译通过。但是请注意,您必须做更多的工作才能以这种方式处理 "identity" 的想法。首先,newUID++ 不是线程安全的,因此您可以使用相同的 "identity" 创建不同的对象。然后,你必须提供一个复制构造函数,除非你想允许相同的 "identity" 可以由内存中的不同对象表示。