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

Bro*_*r93 4 c++ constructor

嘿伙计,所以我在我的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;
};
Run Code Online (Sandbox Code Playgroud)

在我的实现文件中,我有

#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;
}
Run Code Online (Sandbox Code Playgroud)

在我的主要课程中

#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
    }

}
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 9

当你这样做

foo=creature(choice);
Run Code Online (Sandbox Code Playgroud)

creature在分配的RHS上创建临时对象.一旦语句完成,即在行尾,就会调用它的析构函数.

没有什么可以解决的,但您可以foo在读入后初始化choice,而不是默认初始化然后分配:

int choice;

cout<<"enter 1 2 or 3 to choose ur monster"<<endl;
cin>>choice;

creature foo(choice);
Run Code Online (Sandbox Code Playgroud)