关于vc++的析构函数的一个弱弱弱的小问题,高手解答一下,谢谢!!

作者在 2010-03-04 19:36:12 发布以下内容
关于构造函数和析构函数的一个小问题:
vc++在类中可以自己设置构造函数和析构函数,在主程序中可以调用析构函数。
问题:1、如果在主程序中调用了一个实例的析构函数那么对接下来的程序运行有什么样的影响?
      2、在主程序中调用析构函数有用么?
      3、析构函数是不是与构造函数成对出现?是否可以单独执行,如果仅仅调用了析构函数是不是没有任何用处??
下边是一段可以运行的代码,在main函数中调用了子类的析构函数。
#include <iostream.h>
#include <conio.h>
class animal
{
public:
    animal()
    {
        cout<<"animal construct"<<endl;
    }
    ~animal()
    {
        cout<<"animal deconstruct"<<endl;
    }
    void sleep()
    {
        cout<<"animal sleep"<<endl;
    }
    void eat()
    {
        cout<<"animal eat"<<endl;
    }
    void breath()
    {
        cout<<"animal breath"<<endl;
    }
};
class fish : public animal
{
public:
    fish()
    {
        cout<<"fish construct"<<endl;
    }
    ~fish()
    {
        cout<<"fish deconstruct"<<endl;
    }
    void breath()
    {
        cout<<"fish bubble\n";
    }
};
void main()
{
    fish fh;
    fh.~fish();        //调用了一次fh的析构函数;
    fh.breath();
    animal an;
    an.breath();
    getch();
    cout<<"\n-------the end of the gatch()--------\n";    //仅仅做一个标记。看析构函数在哪里开始运行。
}
程序运行的结果为:
animal construct
fish construct
fish deconstruct          //调用fh的析构函数运行结果;
animal deconstruct        //fh的析构函数调用了,又没有新的构造函数运行,为什么运行fh.breath()还有结果?
fish bubble
animal construct
animal breath
-------the end of the gatch()--------
animal deconstruct
fish deconstruct          //fh的析构函数一定调用了,在这里又运行一遍???这是为什么呢?
animal deconstruct
press any key ton continue
从运行的结果来看fh的构造函数运行了1次,而fh的析构函数“fish deconstruct”运行了两次。这里就是我的问题三的内容,是不是单独调用析构函数是没有任何作用的??
默认分类 | 阅读 1108 次
文章评论,共2条
lijm1989
2010-03-14 16:48
1
无意中路过。。不知道友友解决了没。。解决了的话。。可以再写一篇解释下,说说自己的看法。<br />
&nbsp; &nbsp;我想提示的是,调用了析构函数不等同了对象被销毁。但对象销毁一定会调用析构函数,可以去看看对象储存在哪?显式地调用析构函数的用法。。。<br />
&nbsp; &nbsp;继续看LZ其它。。。
liqiangzk982(作者)
2010-03-18 17:49
2
构造函数和析构函数都是提供给系统调用的,系统调用构造函数分配一个具体的物理空间来构造一个具体的对象,系统调用析构函数来释放这个对象的空间。<br />
<br />
非系统调用是不会有任何做的用。非系统可以调用析构函数,如同对普通的函数调用一样执行一下改函数&quot;{}&quot;内的语句。
游客请输入验证码