标题可能不是很清楚,我解释一下:我只是想在一个字符串被销毁时显示一条消息,所以我这样做了:
std::string::~std::string(void)
{
std::cout << "Destroyed string" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
它没有编译,然后我尝试了这个:
namespace std
{
string::~string(void)
{
cout << "Destroyed string" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
而且它也不起作用,所以有没有办法做我想做的事?谢谢你的帮助。
无法向已定义析构函数的现有类添加自定义析构函数行为。而且; 您不能(也不应该!)修改std::string使用继承的行为。
如果你想要一个具有自定义行为的析构函数,你必须滚动你自己的类来做到这一点。您也许可以std::string通过创建一个仅将字符串作为其唯一成员的类来“包装” a :
struct StringWrapper
{
std::string value;
StringWrapper() {}
~StringWrapper()
{
// Do something here when StringWrapper is destroyed
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |