析构函数的顺序

kdhug886
#include <iostream>
#include <cstring>
using namespace std;

class Ghost{
public:
    Ghost(){
        strcpy(name, "");
        cout << "Ghost(" << name <<")" <<endl;
    }

    Ghost(char n[]){
        strcpy(name, n);
        cout << "Ghost(" << name << ")" << endl;
    }
    ~Ghost(){
        cout <<"~Ghost(" << name << ")" << endl;
    }

private:
    char name[20];
};

class PacMan{
public:
    PacMan(){
        inky = new Ghost("Inky");
        pinky = NULL;
        cout << "PacMan()" << endl;
    }

    PacMan(Ghost* other){
        inky = NULL;
        pinky = other;
        cout << "PacMan(other)" << endl;
    }

    ~PacMan(){
        if (inky!= NULL)
            delete inky;
        cout <<"~PacMan()" << endl;
    }

private:
    Ghost blinky;
    Ghost *inky;
    Ghost *pinky;
};

int main(){
    PacMan pm1;
    Ghost* other = new Ghost("other");
    PacMan* pm2 = new PacMan(other);

    delete pm2;
    delete other;

    return 0;
}

对于这个程序,它输出:

Ghost()
Ghost(Inky)
PacMan()
Ghost(other)
Ghost()
PacMan(other)
~PacMan()
~Ghost()
~Ghost(other)
~Ghost(Inky)
~PacMan()
~Ghost()

我想知道第一个输出Ghost()来自哪里,为什么最后三个输出不是

~PacMan()
~Ghost(Inky)
~Ghost()

我认为析构函数的顺序与构造函数的顺序相反,是真的吗?

越轨者

第一个 Ghost 是PacMan会员blinky

关于最后一个命令:销毁pm1executes

~PacMan(){
        if (inky!= NULL)
            delete inky;
        cout <<"~PacMan()" << endl;
    }  

然后blinky也被删除了。
如果你想要相反的顺序,你必须在这里写。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章