c++基础(析构函数)

作者: zidea | 来源:发表于2019-04-30 11:57 被阅读3次
    Cplusplus-tutorial-in-hindi.jpg
    析构作为构造函数反义词,在我们类释放内存时候进行一些工作,析构函数的定义是在类名称前面加上~的方法,为演示类的机构函数被调用我们将创建好的类在一个函数中实例化。这样他的生命周期就是在这个函数作用域,函数结束后,他也就是被从栈中释放掉从而调用其析构函数。
    #include <iostream>
    
    class Pointer
    {
      public:
        float x, y;
    
        Pointer()
        {
            std::cout << "create Pointer" << std::endl;
        }
    
        ~Pointer()
        {
            std::cout << "deconstruct Pointer" << std::endl;
        }
    
        void Position()
        {
            std::cout << x << y << std::endl;
        }
    };
    
    void func()
    {
        Pointer pointer;
        pointer.Position();
    }
    
    int main(int argc, char const *argv[])
    {
        func();
        std::cin.get();
    }
    
    
    create Pointer
    00
    deconstruct Pointer
    

    也可以直接调用析构函数

    pointer.~Pointer();
    

    相关文章

      网友评论

        本文标题:c++基础(析构函数)

        本文链接:https://www.haomeiwen.com/subject/msbmnqtx.html