首页 > 解决方案 > C++ 中的析构函数输出

问题描述

以下代码不会打印“调用了析构函数”。为什么?但是,我的书把它打印出来了。如何打印析构函数语句?请建议。

#include <iostream>
using namespace std;

class HelloWorld
{
public:
  //Constructor
  HelloWorld()
  {
  cout<<"Constructor is called"<<endl;
  }
 
  //Destructor
  ~HelloWorld()
  {
   cout<<"Destructor is called"<<endl;
   }
};

int main()
{
   //Object created
   HelloWorld obj;

   system("PAUSE");
   return 0;
}

标签: c++

解决方案


尝试这个:

int main()
{
   { // start a scope
       //Object created
       HelloWorld obj;
   } // scope ends here, obj will be deleted here
  
   // now pause so you can see the output before program ends.
   system("PAUSE");

   return 0; 
}

推荐阅读