析构函数的顺序

时间:2017-05-20 13:49:59

标签: c++ class destructor

#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()

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

1 个答案:

答案 0 :(得分:0)

第一个Ghost是PacMan成员blinky

关于最后一个订单:销毁pm1 exectutes

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

然后blinky也会被删除 如果你想要相反的顺序,你可以在这里写下来。