gpt4 book ai didi

c++ - 为什么我的析构函数被调用,我该如何修复它

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:53 26 4
gpt4 key购买 nike

<分区>

我的 C++ 程序中的析构函数有问题。当我运行程序并获取用户输入时,它突然调用析构函数,然后 cout 甚至无法在语句中打印。假设用户输入将是一个,因为我将这部分代码设计为仅接受输入 1。我认为当您离开范围时会调用析构函数,所以我认为至少应该在 cout 之后调用析构函数我将在下面评论的 if 语句,以使你们更容易阅读。如果有人可以解释我的错误并纠正它,那就太好了!在我的头文件中有

#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>

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
}

}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com