简体   繁体   中英

Constructor and Destructor in C++

Can you tell why i don't add "getch()" or "system("pause")", the result is right in the first code else in the second code display to lack code in part destructor

    #include "iostream.h"
    class chucmung1
    {
     public :
         chucmung1()
         {
                    cout <<"chuc mung ban nam moi an khang thinh vuong\n";

         }
         ~chucmung1()
         {
                     cout <<"Nam Tan Ty\n";
         }


    };

  //  the first code
     int main()
     {
      chucmung1 object;
      system("pause > NULL");    
     }

  // the second code 
        int main()
     {
      chucmung1 object;
     } 

In the first code, the result is "chuc mung ban nam moi an khang thinh vuong"

In the second code, the result is "chuc mung ban nam moi an khang thinh vuong Nam Tan Ty" In this case when console don't pause after display result.

Can you tell why i don't add "getch()" or "system("pause")", the result is right in the first code

The object goes out of scope and is destructed when main() exits. There is nothing in that code sample that is preventing main() from exiting, thus the object is being destroyed without delay.

else in the second code display to lack code in part destructor

The getch / pause is delaying main() from exiting, and the object is still in scope at the time of the pause, so it is has not been destructed yet.

If you want the object to be destructed before pausing the code, you can put the object into another scope so it gets destructed earlier:

int main()
{
    {
        chucmung1 object;
    }
    system("pause > NULL");    
}

在这两种情况下,输出都是相同的,尽管在第一种情况下,析构函数在暂停之后运行,但前提是您不按control-C或control-break来退出暂停 ...这将在终止程序之前终止程序析构函数有机会运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM