#include <iostream>
using namespace std;
class Tester {
public:
Tester(int x);
~Tester();
int who;
} Tester_g_1(1) , Tester_g_2(2);
Tester::Tester(int id) {
cout << "Intializing" << id << endl ;
who = id;
}
Tester::~Tester() {
cout << "Destroying" << who << endl;
}
int main() {
Tester localObj(3);
cout << "This is not the first line to be displayed";
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
Intializing1
Intializing2
Intializing3
This is not the first line to be displayedPress any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
为什么析构函数dodes中的语句不起作用? 使用中: 编译器 - microsoft visual c ++ 2010 Express OS - Win7
Mat*_*lia 10
localObj当被破坏main终止(因为它的它的范围),这恰好经过的system("pause").你按一个键,析构函数会运行,但窗口会立即关闭,所以你看不到它.
要查看析构函数的文本,您必须从命令行运行程序,或使用"运行"菜单中的"启动程序而不调试"项目(IIRC VS菜单)(热键为Ctrl+ F5- 谢谢@Cody灰色).在可执行文件终止后,这会添加"按任意键继续",这样您就可以看到析构函数写入的文本.
查看析构函数运行的另一种方法是将变量封装在较小的范围内,您可以这样轻松地执行此操作:
// ...
int main() {
{ // the braces create a new scope...
Tester localObj(3);
cout<<"Inside the Tester scope..."<<endl;
} // ... that ends here
cout << "... outside the Tester scope!";
cout<<"Press Enter to exit...";
cin.ignore();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,system("pause")是丑陋和不便携的; 你应该避免它.
| 归档时间: |
|
| 查看次数: |
3568 次 |
| 最近记录: |