析构函数的输出

Destructor's Output

本文关键字:输出 析构函数      更新时间:2023-10-16

这是我的代码

在文件中卷饼.cpp

#include "Burrito.h"
#include <iostream>
using namespace std;
Burrito::Burrito(){}
void Burrito::printCrap(){cout<< "something"<<endl;}
void Burrito::constante() const{cout<<"this aint gonna change"<<endl;}
Burrito::~Burrito(){cout<<"deconstructed"<<endl;}

在文件中 卷饼.h

#ifndef BURRITO_H
#define BURRITO_H
class Burrito
{public:
        Burrito();
        void printCrap();
        void constante() const;
        ~Burrito();};
#endif // BURRITO_H

在主文件主文件中.cpp

#include <iostream>
#include "Burrito.h"
using namespace std;
int main()
{
    Burrito so;
    Burrito *sagar = &so;
    so.printCrap();
    sagar->printCrap();
  const Burrito constObject;
    constObject.constante();
    return 0;
}

我是初学者,这是我的查询。我试图了解desctructor,这段代码表现良好,除了它运行析构函数2次,所以这个程序的结果是这样的:

something
something
this aint gonna change
deconstructed
deconstructed

为什么它显示两次"去结构"?

您定义了类的两个对象

#include <iostream>
#include "Burrito.h"
using namespace std;
int main()
{
    Burrito so;
    ^^^^^^^^^^^
    Burrito *sagar = &so;
    so.printCrap();
    sagar->printCrap();
  const Burrito constObject;
  ^^^^^^^^^^^^^^^^^^^^^^^^^^
    constObject.constante();
    return 0;
}

所以这两个对象被破坏了。程序中未创建该类的其他对象。

指针的声明sagar

Burrito *sagar = &so;

不创建类的对象。指针指向已创建的对象so

许多指针可以同时引用同一对象,但该对象只会被销毁一次。

例如,如果您写

Burrito *sagar = new Burrito;

然后

delete sagar;

然后在变量sagar的声明中,再创建一个类的对象,然后使用运算符delete可以删除它。在这种情况下,将调用对象的析构函数。

您正在创建 2 个 Burrito() 实例。

一个是Burrito so;
另一个是const Burrito constObject;

因此,当程序完成时,它们将被销毁。

这就是您获得两次输出的原因。

您已经定义了两个 Burrito 实例 - so 和 constObject;因此,每个实例调用一次析构函数(注意:析构函数,而不是"解构函数")。

为了明确正在创建、操作和销毁的对象,您可能需要修改类以包含name字段,仅用于演示目的:

墨西哥卷饼

#ifndef BURRITO_H
#define BURRITO_H
class Burrito
{private: char *name;
 public:
        Burrito(char *nm);
        void printCrap();
        void constante() const;
        ~Burrito();};
#endif // BURRITO_H

墨西哥卷饼.cpp

#include "Burrito.h"
#include <iostream>
using namespace std;
Burrito::Burrito(char *nm){ name = nm; cout << "constructed " << name << endl;}
void Burrito::printCrap(){cout<< name << ": something"<<endl;}
void Burrito::constante() const{cout<< name << ": this aint gonna change"<<endl;}
Burrito::~Burrito(){cout<<"destroyed " << name <<endl;}

主.cpp

#include <iostream>
#include "Burrito.h"
using namespace std;
int main()
{
    Burrito so("so");
    Burrito *sagar = &so;
    so.printCrap();
    sagar->printCrap();
  const Burrito constObject("constObject");
    constObject.constante();
    return 0;
}

编译和运行上述结果:

constructed so
so: something
so: something
constructed constObject
constObject: this aint gonna change
destroyed constObject
destroyed so

祝你好运。

您在主 AND 和so对象的末尾constObject销毁了对象,两者都被销毁,因此它们都打印了此消息。