首页 > 其他分享 >36.智能指针类

36.智能指针类

时间:2022-10-14 18:55:53浏览次数:43  
标签:SmartPoint sm 函数 36 pMaker 智能 析构 Maker 指针

程序1:

#pragma warning(disable:4996)
//2022年10月13日21:47:46
#include <iostream>
using namespace std;

class Maker
{
public:
    Maker()
    {
        cout << "无参构造" << endl;
    }
    void printMaker()
    {
        cout << "hello world" << endl;
    }
    ~Maker()
    {
        cout << "析构函数" << endl;
    }
};

class SmartPoint
{
public:
    SmartPoint(Maker *m)
    {
        this->pMaker = m;
    }
    ~SmartPoint()
    {
        if( this->pMaker != NULL )
        {
            cout << "SmartPoint 析构函数" << endl;
            delete this->pMaker;
            this->pMaker = NULL;
        }
    }

private:
    Maker *pMaker;
};

void test01()
{
    Maker *p = new Maker;

    SmartPoint sm(p);//栈区、会调用析构函数

}

int main()
{
    test01();

    system("pause");
    return EXIT_SUCCESS;
}

输出结果:

无参构造
SmartPoint 析构函数
析构函数
请按任意键继续. . .


程序2:

#pragma warning(disable:4996)
//2022年10月13日21:47:46
#include <iostream>
using namespace std;

class Maker
{
public:
    Maker()
    {
        cout << "无参构造" << endl;
    }
    void printMaker()
    {
        cout << "hello world" << endl;
    }
    ~Maker()
    {
        cout << "析构函数" << endl;
    }
};

class SmartPoint
{
public:
    SmartPoint(Maker *m)
    {
        this->pMaker = m;
    }
    //重载指针运算符
    Maker *operator->()
    {
        return this->pMaker;
    }
    ~SmartPoint()
    {
        if( this->pMaker != NULL )
        {
            cout << "SmartPoint 析构函数" << endl;
            delete this->pMaker;
            this->pMaker = NULL;
        }
    }

private:
    Maker *pMaker;
};

void test01()
{
    Maker *p = new Maker;

    SmartPoint sm(p);//栈区、会调用析构函数
    //当test01()函数结束时,会调用SmartPoint的析构函数,在这析构函数中delete的对象,会调用Maker的析构函数
}

void test02()
{
    Maker *p = new Maker;

    SmartPoint sm(p);//栈区、会调用析构函数
    //sm-> ==> pMaker->
    sm->printMaker();
}

int main()
{
    test02();

    system("pause");
    return EXIT_SUCCESS;
}

输出结果:

无参构造
hello world
SmartPoint 析构函数
析构函数
请按任意键继续. . .


标签:SmartPoint,sm,函数,36,pMaker,智能,析构,Maker,指针
From: https://www.cnblogs.com/codemagiciant/p/16792654.html

相关文章