分类: C/C++
2013-02-25 14:49:31
4. 解引用(*)操作符的重载
解引用操作符是一元操作符;一般应用于智能指针。
格式:
Type & operator * ();
const Type& operator * () const;
实例:
#include
#include
using namespace std;
class CA;
// 智能指针类定义
class C_Ptr
{
C_Ptr(int *p): ip(p), use(1) { cout<< " init: use = " << use << ", *ip=" << *ip<
int *ip; // 指针
int use; // 使用计数
friend class CA;
};
class CA
{
public:
CA(int*p, int v): ptr(new C_Ptr(p)), val(v) {}
CA(const CA& C): ptr(C.ptr), val(C.val) {++ptr->use;} // 拷贝时需要将应用计数+1
CA& operator = (const CA& C);
~CA(){
cout << "~CA(): use = " << ptr->use << endl;
if(--ptr->use == 0)
{
cout << "free C_Ptr" <
}
}
int& operator*() { return *ptr->ip;}
private:
C_Ptr *ptr;
int val;
};
CA& CA::operator = (const CA& C)
{
if( -- this->ptr->use == 0)
{
cout << "operator= free C_Ptr " << endl;
delete this->ptr; // 释放*this 原来指向的内存,否则 *this ->ptr 指向的内存将被泄露;
}
this->val = C.val;
++this->ptr->use; // 赋值时需要将应用计数+1
return *this;
}
int main()
{
int idata = 6;
CA A(&idata, 0);
CA B(A);
CA C(&idata, 1);
cout << *A <
cout << *A <
*C = 20;
cout << *A <
return 1;
}
函数输出:
init: use = 1, *ip=6
init: use = 1, *ip=6
6
10
operator= free C_Ptr
20
~CA(): use = 3
~CA(): use = 2
~CA(): use = 1
free C_Ptr