析构函数的输出

Destructor's Output

这是我的代码

在文件中 Burrito.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;}

在文件中 Burrito.h

#ifndef BURRITO_H
#define BURRITO_H

class Burrito
{public:
        Burrito();
        void printCrap();
        void constante() const;
        ~Burrito();};

#endif // BURRITO_H

并且在主文件中 main.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

为什么显示 "deconstrcuted" 两次?

您定义了 class

的两个对象
#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;
}

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

指针的声明sagar

Burrito *sagar = &so;

不创建class的对象。指针指向已经创建的对象so.

多个指针可以同时指向同一个对象,但对象只会被销毁一次。

如果你写了例如

Burrito *sagar = new Burrito;

然后

delete sagar;

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

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

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

因此,它们在程序结束时被破坏。

这就是为什么您得到两次输出的原因。

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

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

为了清楚地说明正在创建、操作和销毁哪个对象,您可能需要修改 class 以包含一个 name 字段,仅用于演示目的:

Burrito.h

#ifndef BURRITO_H
#define BURRITO_H

class Burrito
{private: char *name;
 public:
        Burrito(char *nm);
        void printCrap();
        void constante() const;
        ~Burrito();};

#endif // BURRITO_H

Burrito.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;}

main.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

祝你好运。