第37课.智能指针分析(重载的综合使用) 1.智能指针(即一个功能完善的类) 注意:智能指针只能用来指向堆空间中的对象或变量

a.指针生命周期结束时主动释放堆空间
b.一片堆空间最多只能由一个指针标识
c.杜绝指针运算和指针比较

解决方案:
a.重载指针特征操作符("->"和"*")
b.只能通过成员对象重载(=, [], ())
c.重载函数不能使用参数
d.只能定义一个重载函数

注意:智能指针只能用来指向堆空间中的对象或变量

eg:

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int i;
public:
    Test(int i)
    {
        cout << "Test(int i)" << endl;
        this->i = i;
    }
    int value()
    {
        return i;
    }
    ~Test ()
    {
        cout << "~Test()" << endl;
    }
};

class Pointer
{
    Test* mp;
public:
    Pointer (Test* p = NULL)                //传入一个地址
    {
        mp = p;                            //把传入的地址赋值给mp
    }
    Pointer (const Pointer& obj)           //注意:一个空间只能由一个指针访问
    {
        mp = obj.mp;
        const_cast<Pointer&>(obj).mp = NULL;        //指针赋值完后,这段需置为空
    }
    Pointer& operator = (const Pointer& obj)
    {
        if(this != &obj)
        {
            //delete mp;
        
            mp = obj.mp;
            const_cast<Pointer&>(obj).mp = NULL;
        }     
        return *this;
    }
    
    Test* operator -> ()            //调用->后会返回一个Test *指针
    {
        return mp;
    }
    Test& operator * ()            //调用*后会返回一个Test的引用
    {
        return *mp;
    }

    bool isNull ()
    {
        return (mp == NULL);
    }
    
    ~Pointer ()
    {
        delete mp;
    }
};

int main()
{
    Pointer p1 = new Test(0);        //分配一个智能指针(类)调用构造函数时,给它一个地址(地址中的内容为0)。
    
    cout << p1->value() << endl;    //p1->value(),(p1 operator ->())->value()。p1指时,返回Test* mp。对象指针。调用它的value()成员函数
                                    //这里两个->一个是重载的版本,一个是内建的版本
    Pointer p2 = p1;
    
    cout << p1.isNull() << endl;
    
    cout << p2->value() << endl;
    
    return 0;
}

第37课.智能指针分析(重载的综合使用)
1.智能指针(即一个功能完善的类)
注意:智能指针只能用来指向堆空间中的对象或变量