gpt4 book ai didi

c++ - 析构函数的输出

转载 作者:行者123 更新时间:2023-11-30 01:12:00 26 4
gpt4 key购买 nike

这是我的代码

在文件 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”?

最佳答案

你定义了类的两个对象

#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 可以将其删除。在这种情况下,将调用对象的析构函数。

关于c++ - 析构函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com