c語言有析構函數嗎,析構函數c+_了解C ++中的析構函數

 2023-11-19 阅读 25 评论 0

摘要:析構函數c+In this tutorial, we are going to understand the concept of destructors in C++, their uses as well as try to implement them in our code. 在本教程中,我們將了解C ++中的析構函數的概念,它們的用法以及嘗試在我們的代碼

析構函數c+

In this tutorial, we are going to understand the concept of destructors in C++, their uses as well as try to implement them in our code.

在本教程中,我們將了解C ++中析構函數的概念,它們的用法以及嘗試在我們的代碼中實現它們。

C ++中的析構函數是什么? (What are the Destructors in C++?)

Theoretically, a Destructor is a member function that is used to destroy or delete an object. It can be user-defined. But if not defined, by default at the time of compilation the compiler generates an inline destructor.

從理論上講, 析構函數是用于破壞或刪除對象的成員函數。 可以是用戶定義的。 但是,如果未定義,默認情況下在編譯時,編譯器會生成一個內聯析構函數。

c語言有析構函數嗎?A destructor is invoked automatically when the object goes out of scope or is explicitly destroyed by the delete operator.

當對象超出范圍或由delete運算符明確銷毀時,析構函數將自動調用。

Now let us look at the syntax of defining a destructor in C++ for a class named example:

現在讓我們來看一下在C ++中為名為example的類定義析構函數的語法:


example::~example()
{//destructor statements;
}

Here, as you can see, the destructor function(~example()) has the same name as that of the class it belongs to.

如您所見,在這里,析構函數( ~example() )與其所屬類的名稱相同。

C哩c哩舞?Note: Remember before defining a destructor in C++:

注意:在C ++中定義析構函數之前, 記住:

  • Destructor name and class name must be same

    析構函數名稱和類名稱必須相同
  • A destructor name should have a tilde(‘~’) before it. For eg. ~example(){}

    析構函數名稱前應帶有波浪號('?') 。 例如。 ?example(){}
  • They must not accept any arguments or return anything to the function call

    他們不得接受任何參數或向函數調用返回任何內容
  • A destructor can be virtual

    析構函數可以是虛擬的
  • Derived classes do not inherit the destructor of their base class

    派生類不繼承其基類的析構函數
  • There can only one destructor in a single class.

    單個類中只能有一個析構函數。

C ++析構函數示例 (C++ Destructors Example)

Now let us take a look at an example where we try to define our destructor for our demo class.

現在,讓我們看一個示例,嘗試為演示類定義析構函數。


#include<iostream>
using namespace std;class demo
{public:int a=10;demo() //constructor{cout<<"Constructor of demo here!"<<endl;}~demo() //destructor{cout<<"Destructor of demo here!"<<endl;}void print_demo() //function{cout<<"printed demo"<<endl;}
};int main()
{demo demo_obj;  //object of class demo createdcout<<demo_obj.a<<endl;demo_obj.print_demo(); //function calledreturn 0;
}  //scope of the object ends

Output:

輸出


Constructor of demo here!
10
printed demo
Destructor of demo here!

c哩c哩歌手?Here,

這里,

  • Inside the demo class, we have initialized and defined a variable as a=10 and a function print_demo() respectively. Further, we have also defined the corresponding constructor – demo() and destructor – ~demo().

    在演示類內部,我們分別初始化和定義了一個變量a=10和一個函數print_demo() 。 此外,我們還定義了相應的構造函數– demo()和析構函數~demo()
  • Inside the main() function we create an object demo_obj that belongs to the above demo class. This leads to the call for the constructor demo().

    main()函數內部,我們創建一個對象demo_obj ,該對象屬于上面的演示類。 這導致對構造函數demo()的調用。
  • Then we also have performed some operations on it like calling the print_demo() function for the object.

    然后,我們還對其執行了一些操作,例如為對象調用print_demo()函數。
  • As soon as the main() function ends, the compiler calls the destructor for the object demo_obj. Which is clear from the above output.

    一旦main()函數結束,編譯器便為對象demo_obj調用析構函數。 從上面的輸出中可以清楚地看出。

明確調用C ++中的析構函數 (Explicitly Calling Destructors in C++)

Apart from the fact that the compiler calls the default or user-defined destructor as soon as an object gets out of scope. The C++ programming language also allows the user to call the destructor for an object explicitly.

除了一個對象超出范圍后,編譯器會調用默認或用戶定義的析構函數這一事實。 C ++編程語言還允許用戶顯式調用對象的析構函數

Let us try to call the destructor ~demo() for our previous example code. We just modify our code inside main().

讓我們嘗試為前面的示例代碼調用析構函數~demo() 。 我們只是在main()修改我們的代碼。


#include<iostream>
using namespace std;class demo
{public:int a=10;demo() //constructor{cout<<"Constructor of demo here!"<<endl;}~demo() //destructor{cout<<"Destructor of demo here!"<<endl;}void print_demo() //function{cout<<"printed demo"<<endl;}
};int main()
{demo obj;obj.print_demo();obj.~demo();return 0;
}

c static?Output:

輸出


Constructor of demo here!
printed demo
Destructor of demo here!
Destructor of demo here!

As you can see, as we create an object the constructor demo() is called.

如您所見,在創建對象時,將調用構造函數demo()

After that, we explicitly call the destructor ~demo() for the object obj. This explains the 3rd line of the output ‘Destructor of demo here!’.

之后,我們顯式調用對象obj的析構函數~demo() 。 這說明了輸出“此處的演示的析構函數!”的第三行

C.c,But, the next line is the result of the default calling of the destructor by the compiler at the end of the main() function(since the scope of the object ends).

但是,下一行是編譯器在main()函數末尾默認調用析構函數的結果(因為對象范圍結束了)。

Note: In case of local variables (the above one) calling the destructor explicitly is not recommended since the destructor will get called?again?at the close ‘}’?of the block in which the local was created.

注意 :如果是局部變量(上面的一個),則不建議顯式調用析構函數,因為析構函數將在創建局部變量的塊的結束處“}”處再次調用。

C ++中的虛擬析構函數 (Virtual Destructors in C++)

Destructors in C++ can also be made virtual. They are useful when we try to delete an instance of a derived class through a pointer to base class.

C ++中的析構函數也可以設為虛擬的。 當我們嘗試通過指向基類的指針刪除派生類的實例時,它們很有用。

c++中析構函數的作用。Now let us look at an example to have a better understanding.

現在讓我們看一個例子,以更好地理解。

虛擬析構函數示例 (Virtual Destructor Example)


#include<iostream>
using namespace std;class Base 
{public:Base(){cout<<"Base Constructor"<<endl;}virtual ~Base(){cout<<"Base Destructor"<<endl;}
};class Derived: public Base 
{public:Derived(){cout<<"Derived Constructor"<<endl;}~Derived(){cout<<"Derived Destructor"<<endl;}
};
int main()
{Base * b = new Derived;delete b;
}

Output:

輸出


Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

Notice, this time we have used the virtual keyword before the base destructor.

注意,這一次我們在基本析構函數之前使用了virtual關鍵字。

c++中析構函數。It is clear from the output that inside the main() function, the instruction Base *b = new Derived leads to the call for constructors Base() and Derived() respectively.

從輸出中很明顯,在main()函數內部,指令Base *b = new Derived導致對構造函數 Base()和Derived()的調用。

While deleting the object b, since this time a virtual destructor is inside the base class, hence first the Derived class’s destructor is called and then the Base class’s destructor is called.

自從刪除對象b以來,由于這一次虛擬析構函數位于基類內部,因此,首先將調用Derived類的析構函數,然后再調用Base類的析構函數。

Note: if the base class destructor is not virtual then, only the base class object will get deleted(since the pointer is of a base class). This would lead to memory leak for the derived object.

注意 :如果基類析構函數不是虛擬的,則僅基類對象將被刪除(因為指針是基類的)。 這將導致派生對象的內存泄漏

為什么要使用析構函數? (Why Destructors?)

C++析構函數,Destructors deallocate memory assigned or allocated to different objects in a program as soon as they go out of scope or are explicitly deleted. If it were not for destructors, then the user would have to individually free memory space allocated to different variables or objects. Which is a pretty hectic task.

一旦析構函數超出范圍或被顯式刪除,則析構函數將取消分配或分配給程序中不同對象的內存。 如果不是析構函數,那么用戶將必須單獨釋放分配給不同變量或對象的內存空間。 這是一項非常繁忙的任務。

This automatic de-allocation of memory not only creates a more user-friendly environment to work but also helps manage memory efficiently.

內存的這種自動重新分配不僅創建了更加用戶友好的工作環境,而且還有助于有效地管理內存。

結論 (Conclusion)

Thus through this tutorial, we learned about destructors in C++. We also understood the working and use by implementing it in our code.

因此,通過本教程,我們了解了C ++中的析構函數 。 我們還通過在代碼中實現它來理解其工作和使用。

析構函數和構造函數,For any questions related to this topic, feel free to use the comments below.

對于與該主題相關的任何問題,請隨時使用以下評論。

參考資料 (References)

  • Destructors – cppreferences

    析構函數– cppreferences
  • Destructors – Microsoft Documentation

    析構函數 – Microsoft文檔
  • Right usage of destructor – StackOverflow Question.

    正確使用析構函數 – StackOverflow問題。

翻譯自: https://www.journaldev.com/37885/destructors-in-c-plus-plus

析構函數c+

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/183203.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息