运算符重载调用析构函数吗_通过构造函数和析构函数打印值的C ++中的new和delete运算符...

运算符重载调用析构函数吗

In C++ programming language, there are two operators 1) new and 2) delete, which are used to manage the memory dynamically i.e. to create, delete the memory at run time (dynamically)

在C ++编程语言中,有两个运算符1) new和2) delete ,它们用于动态管理内存,即在运行时(动态)创建,删除内存

Prerequisite: new and delete operators in C++ programming

先决条件: C ++编程中的new和delete运算符

Let’s understand, when 'new' and 'delete' are used?

让我们了解一下, 何时使用“新”和“删除”?

new is used to declare memory blocks at run time (dynamically). While, delete is used to delete/free the memory which has been declared dynamically.

new用于在运行时声明内存块(动态)。 同时, delete用于删除/释放已动态声明的内存。

C ++中的new和delete的示例 (Example of new and delete in C++)

In the given program, we are using new to allocate memory to the class object and delete/free is using to delete the reference of the pointer that will force. There is a class named sample and it has a constructor sample() and a destructor ~sample().

在给定的程序中,我们使用new来为类对象分配内存,而delete / free使用的是删除将强制执行的指针的引用。 有一个名为sample的类,它具有一个构造函数sample()和一个析构函数〜sample() 。

Consider the program:



考虑该程序:

</ s> </ s> </ s>
#include <iostream>
using namespace std;

class sample
{
    public:
	sample()
	{
		cout<<"Hi ";
	}
	~sample()
	{
		cout<<"Bye ";
	}
};

int main() 
{
	sample *obj = new sample();
	delete(obj);
	return 0;
}

Output

输出量

    Hi Bye 

You can see, "Hi" is written in the constructor (sample()) while "Bye" is written in the destructor (~sample()).

您会看到, “ Hi”是写在构造函数( sample() )中的,而“ Bye”是写在析构函数( 〜sample() )中的。

Therefore, when object "obj" is creating, constructor will be called and print "Hi", same as when object is going to be freed using delete(obj), destructor (~sample()) will be called and print "Bye".

因此,当创建对象“ obj”时 ,将调用构造函数并显示“ Hi” ,这与将要使用delete(obj)释放对象时相同,将调用析构函数( 〜sample() )并显示“ Bye”

翻译自: https://www.includehelp.com/cpp-programs/new-and-delete-with-printing-value-with-constructor-and-destructor.aspx

运算符重载调用析构函数吗

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值