为什么一个类只有一个析构函数? [英] Why a class has only one destructor?

查看:1366
本文介绍了为什么一个类只有一个析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被问过一个问题,一个类有多个构造函数但为什么它只有一个析构函数

I have been asked a question as, a class has multiple constructors but why it has only one destructor?

我在下面给出了示例,

class abc
{
public:
    int a;
    abc()
    {
        cout << "Default\n";
    }
    abc(int)
    {
        cout << "Int\n";
    }
    ~abc()
    {
        cout << "Destructor\n";
    }
};
int main()
{
    abc ab;
    abc a(5);
}

我之前解释过abc a(5)被调用的析构函数将被调用所以,在特定的时间点只有一个对象。我现在在我的电脑上运行上面的代码,但它给我输出为

And I explained as before abc a(5); gets called destructor will get called so, there will only one object at a particular point of time. I ran the above code now in my PC but it gave me output as

Default
Int
Destructor
Destructor

如果是这样,那么为什么我们析构函数

If this is so then why do we haveone destructor ?

推荐答案

析构函数没有参数,所以只能有一个。然而,你可以有多个构造函数,因为你可以重载构造函数,这是不可能与析构函数。
还要添加,析构函数用于终止类的实例,并释放它正在使用的所有资源。

A destructor doesn't have parameters, so there can be only one. However you can have more than 1 constructor since you can overload the constructor which is not possible with Destructors. Also to add that destructor is used to terminate the instance of the class and release all resources which it is using. There is nothing optional when you are destroying the object. The instance will not exist when destructor will be called.

当一个非常有限的例子解释它,但它的喜欢,如果你有1苹果和1番石榴,然后你会使用1刀切割它。 ;)

Although a very wierd example to explain it but its like if you have 1 Apple and 1 Guava then you will use the 1 knife to cut it. ;)

Destructors 通常用于释放内存,并在对象被销毁时对类对象及其类成员进行其他清理。当对象超出范围或被显式删除时,会为类对象调用析构函数。

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.


before abc a(5)被调用的析构函数将被调用

before abc a(5); gets called destructor will get called

不会被调用,因为析构函数被隐式调用。

No it will not be called as Destructors are called implicitly.

在旁注: -

但是如果你打算明确调用析构函数程序员不会建议),那么完全是你的责任来管理资源。编译器不会处理它,它可能会导致严重的内存问题。您可以查看此 C ++常见问题 解释它。

However if you plan to call the Destructor explicitly(which most of the programmers will not suggest) then it would be completely your responsibility to manage the resources. The compiler will not take care of it and it may result in serious memory issues. You may check this C++ FAQ explaining it.

这篇关于为什么一个类只有一个析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆