今天和大家分享一个我在定义类的析构函数时,发现不能显示的调用我定义的析构函数,这是为什么呢??
#include<iostream>
using namespace std;
#include<string.h>
class String
{
public:
String(const char* str = "")
{
if (str == NULL)
{
_str = new char[1];
*_str = '\0';
}
else
{
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
}
~String()
{
if (_str)
{
delete[] _str;
_str = NULL;
}
cout << this << endl;
}
private:
char* _str;
};
int main()
{
String s1("hello");
String s2(s1);
system("pause");
return 0;
}
看出问题出在哪了吗??似乎析构函数定义的没有问题啊??这是因为你在main函数中多加了句system("pause");就是这句,为什么呢??它的作用本来是防止程序运行结束闪退的问题,但是当程序运行到system("pause"); 时,会输出“请按任意键继续。。。”此时,主函数还未执行完,String变量为局部变量,只有等到函数体退出时,才会销毁,可是如果楼主你按下任意键进,函数体执行完毕,会输出“this指针的内容”,但由于输出窗口随后就关闭了,你是无法看到的。
解决办法:1.去掉system("pause");按F10进行调试
2.
int main()
{
{
String s1("hello");
String s2(s1);}
system("pause");
return 0;
}