一蜘猫 2022-02-03 20:04 采纳率: 75%
浏览 23
已结题

成员函数里面new的地址怎么在调用结束后自动delete呀

class MyInteger
{
private:
    int m_Num;

public:
    MyInteger() : m_Num(0) {}
    ~MyInteger() {}

public:
    // 前置递增重载
    MyInteger &operator++()
    {
        m_Num++;      // 先进行++运算
        return *this; // 返回自身,解引用 this指针
    }
    // 后置递增重载
    MyInteger& operator++(int)
    {
    // void operator++(int)  int代表占位参数,可以区分前置和后置递增
    // 后置递增要返回值 MyInteger operator++(int),因为 temp 是局部变量,函数结束后就释放了
        // 实现先返回自身后运算结果
        // 先记录当前值,递增,返回记录的值
        // MyInteger temp = *this;
        // this->m_Num++;
        // return temp;
        
        // test : 利用new
        MyInteger* temp = new MyInteger(*this);
        this->m_Num++;
        return *temp;
    }

MyInteger* temp = new MyInteger(*this);这一步new的内存怎么释放掉

  • 写回答

2条回答 默认 最新

  • 关注

    img

    参考如下:

    #include <iostream>
    using namespace std;
    class MyInteger
    {
    private:
        int m_Num;
    
    public:
        MyInteger() : m_Num(0) {}
        //添加了两个构造函数
        MyInteger(int n):m_Num(n){}
        MyInteger(MyInteger& s)
        {
            m_Num = s.m_Num;
        }
        ~MyInteger() {}
    
    public:
    
        // 前置递增重载
        MyInteger &operator++()
        {
            m_Num++;      // 先进行++运算
            return *this; // 返回自身,解引用 this指针
        }
        // 后置递增重载,注意这里的&删掉了
        MyInteger operator++(int)
        {
            // void operator++(int)  int代表占位参数,可以区分前置和后置递增
            // 后置递增要返回值 MyInteger operator++(int),因为 temp 是局部变量,函数结束后就释放了
            // 实现先返回自身后运算结果
            // 先记录当前值,递增,返回记录的值
            // MyInteger temp = *this;
            // this->m_Num++;
            // return temp;
            // test : 利用new
            //MyInteger* temp = new MyInteger(*this);
            MyInteger temp(*this);
            
            this->m_Num++;
            return temp;
        }
        //重载输出运算符
        friend ostream& operator<<(ostream &os,MyInteger &c);
        
    };
    
    int main()
    {
        MyInteger myint(0);
        cout << myint << endl;       // 0
        cout << myint++ << endl;     // 0
        cout << myint << endl;       // 1
    
        return 0;
    }
    ostream& operator<<(ostream &os,MyInteger &c)
    {
        os << c.m_Num;
        return os;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月12日
  • 已采纳回答 2月4日
  • 创建了问题 2月3日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效