【发布时间】:2015-08-10 03:03:57
【问题描述】:
我的 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
}
}
【问题讨论】:
-
它被称为“析构函数”。
-
在
foo = creature(choice);中,您创建一个匿名实例(creature(choice)),在foo上调用creature & operator=(const creature &),然后销毁该匿名实例。另外,它是“析构函数”,顺便说一句。 -
您的
count变量并未反映实际情况。您未能添加复制构造函数和赋值运算符来计算这些实例。相反,您正在减少您甚至没有跟踪的对象实例的计数。 -
@TheParamagneticCroissant:这几乎不值得指出。即使没有上下文,
deconstructor也完美地描述了它是什么。
标签: c++ constructor