为什么我的析构函数被调用了,我该如何解决它。

30 浏览
0 Comments

为什么我的析构函数被调用了,我该如何解决它。

这个问题已经有了答案:

什么是三大法则?

我在我的 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日
0
0 Comments

正如juanchopanza在他的回答中指出的那样,这行代码

foo = creature(choice);

在将临时creature对象分配给foo之前创建了它。如果你不想这样发生,则应该使用下面的方式创建它

creature foo(choice);

0
0 Comments

当您这样做时

foo=creature(choice);

在赋值语句的右侧创建了一个临时的creature对象。一旦语句完成,即在行末,就会调用它的析构函数。

实际上没有什么需要修复的,但您可以在读取choice后初始化foo,而不是默认初始化然后再进行赋值:

int choice;
cout<<"enter 1 2 or 3 to choose ur monster"<>choice;
creature foo(choice);

0