zoukankan      html  css  js  c++  java
  • 析构

    当我们新建一个类的实例时,构造函数会被调用,当我们这个实例被销毁时,析构函数被调用。构造函数是将需要用到的东西进行初始化,那么同样的,析构函数是与初始化相反的过程,用来清空内存以便于接下来使用。对应的,如果使用new来申请空间,那么需要用delete来进行析构,如果只是基于堆栈来进行空间申请,那么当实例被删除的时候,析构函数就会被调用。

    #include<iostream>
    
    class Entity
    {
    public:
        float X,Y;
        Entity()
        {
            X=0.0f;
            Y=0.0f;
            std::cout<<"Created Entity!"<<std::endl;
        }
    
        ~Entity()
        {
            std::cout<<"Destoryed Entity!"<<std::endl;
        }
        void Print()
        {
            std::cout<<X<<","<<Y<<std::endl;
        }
    };
    
    void Function()
    {
        Entity e;
        e.Print();
    }
    
    int main()
    {
        Function();
        std::cin.get();
    }

    设置断点进行单步调试会发现,当执行语句Entity e时,调用构造函数,当执行完Function()后,调用析构函数。析构函数与可以手动执行,,将Function函数如下修改

    void Function()
    {
        Entity e;
        e.Print();
        e.~Entity();
    }

     但是手动调用其实并不常见。

  • 相关阅读:
    leetcode297
    leetcode4
    leetcode23
    leetcode72
    leetcode239
    leetcode42
    leetcode128
    leetcode998
    SAP MM GR-based IV, 无GR不能IV?
    小科普:机器学习中的粒子群优化算法!
  • 原文地址:https://www.cnblogs.com/wangtianning1223/p/12679795.html
Copyright © 2011-2022 走看看