C++ 44 之 指针运算符的重载

 

#include <iostream>
#include <string>
using namespace std;

class Students04{
public:
    int m_age;
    Students04(int age){
        this->m_age = age;
    }
    void showAge(){
        cout << "年龄是: " << this->m_age << endl;
    }
    ~Students04(){
        cout << "析构" << endl;
    }
};

// 利用智能指针管理new出来的students04对象的delete操作
class SmartPoint{
public:
    Students04* m_stu;
    SmartPoint(Students04* stu){
        this->m_stu = stu;
    }
    ~SmartPoint(){
        if(this->m_stu){
            delete this->m_stu;
            this->m_stu = NULL;
            cout << "智能指针析构"<< endl;
        }
    }

    // 重载->
    Students04* operator->(){
        return this->m_stu;
    }
     // 重载*
    Students04& operator*(){
        return *(this->m_stu);
    }

};

int main()
{
    // 堆中申请空间
    // Students04* stu1 = new Students04(18); // 显示法
    // stu1->showAge();  //方法1:
    // (*stu1).showAge();  //方法2:解引用法
    // delete stu1;

    
    SmartPoint sp(new Students04(18));  // sp 是个实例化对象 对象不是指针,不能用->符号,所以要重载 sp->

    // sp 无法实现指针效果,再次重载->
    // sp 是个实例化对象 对象不是指针,不能用->符号,所以要重载 sp->
    // sp->->showAge();  // sp->  == this->m_stu
    // this->m_stu->showAge();
    // sp->->showAge();
    // 系统认为太丑了,所以两组箭头间化为1组
    sp->showAge();

    // sp无法实现指针效果,再次重载*
    (*sp).showAge();


    return 0;
}

相关推荐

  1. C++ 中运算符重载(二)

    2024-06-16 06:18:01       53 阅读
  2. c++:new和delete运算符重载

    2024-06-16 06:18:01       57 阅读
  3. C# 运算符重载 之前小总结

    2024-06-16 06:18:01       42 阅读
  4. C++运算符重载

    2024-06-16 06:18:01       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-16 06:18:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-16 06:18:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-16 06:18:01       82 阅读
  4. Python语言-面向对象

    2024-06-16 06:18:01       91 阅读

热门阅读

  1. Selenium 定位编辑框有span

    2024-06-16 06:18:01       30 阅读
  2. 高考毕业季--浅谈自己感想

    2024-06-16 06:18:01       23 阅读
  3. spring boot 多个项目整合,打包成可依赖的包

    2024-06-16 06:18:01       28 阅读
  4. QML Controls模块-标准对话框用法说明

    2024-06-16 06:18:01       24 阅读
  5. 【泛微系统】日常工作中经常会用到的快捷地址

    2024-06-16 06:18:01       34 阅读
  6. 大数据开发语言Scala入门

    2024-06-16 06:18:01       34 阅读