【发布时间】:2017-10-20 13:35:01
【问题描述】:
#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()
我认为析构函数的顺序与构造函数的顺序相反,是真的吗?
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 edit 您的问题包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
delete nullptr;是合法的。if ( p != nullptr ) delete p;是一种反模式。
标签: c++ class destructor