引用计数器实现,= 运算符重载错误
Reference counter implementation, = operator overloading error
我正在这个程序中实现引用计数。
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;
}
没有故意编写一些函数。
编译时出现此错误
In member function ‘ref_count& ref_count::operator=(const ref_count&)’:
no match for ‘operator==’ in ‘*(ref_count*)this == r1’
我以前总是这样写,但这不是编译。
只需使用
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)
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板