为什么我的析构函数被调用了,我该如何解决它。
为什么我的析构函数被调用了,我该如何解决它。
这个问题已经有了答案:
我在我的 c++ 程序中有一个析构函数的问题。当我运行程序并获取用户输入时,它会在 cout 可以打印语句的内部之前突然调用析构函数。假设用户输入将是1,因为我设计了代码的这一部分只接受输入1。我原以为离开作用域时析构函数才会被调用,所以我认为析构函数至少应该在后面if语句内的cout之后被调用,我会在下面注释这个部分,以便让大家更容易阅读。如果有人能解释我的错误并进行更正,那将太棒了!在我的头文件中,我有
#include #include #include #include using namespace std; class creature{ public: creature();//default constructor creature(int a); ~creature();//desconstructor string getName();//accessor for the name static int getNumObjects(); private: string name; int happy_level; static int count; };
在我的实现文件中,我也有
#include "creature.h" int creature::count=0;//initialize static member variable creature::creature(){//default constructor name="bob"; ++numberobject; cout<<"The default constructor is being called"<<endl; } creature::creature(int a) { if(a==1) { name="billybob"; } else if(a==2) { name="bobbilly"; } else if(a==3) { name="bobbertyo"; happy_level=1; } } creature::~creature() { cout<<"The destructor is now being called"<<endl; cout<<creature::getName()<<" is destroyed."<<endl; --count; cout<<"Now you have a total number of "<<creature::getNumObjects()<<" creature"<<endl; }
而在我的主类中,我有
#include "creature.h" int main() { creature foo;//this is where the default constructor gets called which is good int choice; cout<<"enter 1 2 or 3 to choose ur monster"<<endl; cin>>choice; foo=creature(choice); if(choice==1) { cout<<"hi"<<endl;//the destructor gets called before hi is printed out and I don't know why thats happening } }
admin 更改状态以发布 2023年5月22日