C++ 参考计数器实现,=运算符重载错误

C++ 参考计数器实现,=运算符重载错误,c++,C++,我正在这个程序中实现引用计数 class plain_class{ public: int ref_count; char *data; plain_class(const char *); ~plain_class(); }; class ref_count{ private: plain_class *p; public: ref_count(const char *); ref_count(const ref_count &

我正在这个程序中实现引用计数

class plain_class{
public: int ref_count;
    char *data;
    plain_class(const char *);      
    ~plain_class();
};
class ref_count{
private:
    plain_class *p;
public:
    ref_count(const char *);
    ref_count(const ref_count &);
    ref_count& operator=(const ref_count &);
    void show_context();
    ~ref_count();
};
ref_count::ref_count(const char *str)
{
p=new plain_class(str);
}
ref_count::ref_count(const ref_count &ref)
{
p=ref.p;
p->ref_count++;
cout<<"reference count value="<<p->ref_count<<endl;
}
ref_count& ref_count::operator=(const ref_count &r1)   //= operator overloaded function
{
if(*(this)==r1){
    cout<<"Initializing to itself"<<endl;
    return *this;
}
p=r1.p;
p->ref_count++;
cout<<"reference count value="<<p->ref_count<<endl;
return *this;
}

int main(int argc, char *argv[])
{
ref_count r1("Hello_world");
r1.show_context();
ref_count r2=r1;
r2=r2;           //Error signature not matching to call = operator overload function
return 0;
}
在我以前的程序中,我总是这样写,但这不是编译。

只需使用

 if(p==r1.p)---> for just pointer check
 or if(this==&r1)---> for object check
 instead of if(*(this)==r1){}
它将工作..

而不是

if(*(this)==r1)
你可能想要

if(this==&r1)
像这样

if(this==&r1){

但这是一种更好的方法,它不检查自我分配。如果您添加新成员,您也必须检查它们。@LuchianGrigore您是对的,我只是为成员变量制作的,但现在在再次编译之后,我发现这也起作用了。.对于不同类型的对象,不能进行自赋值。@WolfP。参考计数r1(“你好世界”);参考计数r2=r1;r2=r2。。。。。。。。。这里r1和r2是ref_count class???@santossahu的对象,代码
(this!=&rhs)
防止自我分配。仅当您尝试(在大多数情况下是意外地)将一个对象分配给自身时,才可能进行自分配,如您的示例中的
r2=r2
。一个对象始终具有相同的类型。保护机制确保您不会同时在同一地址上写入和读取。
if(this==&r1){