当前位置 博文首页 > m0_53328774的博客:C++病历:constructor&destructor

    m0_53328774的博客:C++病历:constructor&destructor

    作者:[db:作者] 时间:2021-07-12 10:15

    constructor and destructor(解构函数与析构函数) constructor and destuctor

    Firstly,我们来看几行代码:

    Point::init()
    class Point{
    public:
    void	init(int x,int y);//init初始化
    void	print() const;
    void	move(int dx,int dy);
    private:
    int x;
    int y;}
    Point a
    

    ;//point这里类里有一个a,却没有对x,y进行初始化,一般c++里面不会清理,更注重效率。很多初学者总是写了一个很小的程序(包括我),没有做初始化就直接编译运行一看没错就起飞了。(很神奇的一件事:但VS中的Debug会帮你做调试,:oxcd,两个oxcd连起来就是国标码中的烫烫烫烫

    a.init(1,2);
    a.move(1,2);
    a.print();
    

    Guaranteed initialization with the constroctor(保证构造函数的对象初始化)
    //其实很想吐槽一下,很多人对constructor的翻译是构造器,他们强烈认为只有constructor function才是构造函数23333333…

    **so~How a constructor does?

    **

    class x{
    	int i;
    	public: x();//实际上这个地方就相当于a.x
    };
    

    总结如下:
    1.constructor的名字和类是相同的
    2.constructor没有返回的类型
    3.constructor在一旦创建时就会被调用
    好了,有请下一位男嘉宾:The destructor(析构函数)

    class y{
    	public:~y();//注意一定要有~
    };
    

    总结如下:
    1.当你的函数将被消灭的时候,destructor就会被调用。
    2.destructor不能有参数
    3.destructor也没有返回类型
    4.destructor会在离开时将申请的内存释放掉

    cs
    下一篇:没有了