0

我想删除一个带有函数的 2 级派生类并将其句柄设置为 null。一段代码会有所帮助:

ref class bob
{
};

ref class bill : public bob
{
};

ref class jack : public bill
{
};

void DeleteX( bob ^% x )
{
  if( x != nullptr )
  {
    delete x;
    x = nullptr;
  }
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
  bill^ one = gcnew jack();
  DeleteX(one);
  System::Diagnostics::Trace::Assert(one == nullptr); //Failed
  return 0;
}

如果我对声明和函数参数使用相同的类型,它就可以工作。但我想在声明中使用中间类型,在函数参数中使用上层类型。请问我该怎么做?

这是我最终使用的解决方案:

template<class T>
void DeleteX( T ^% x )
{
  if( x != nullptr )
  {
    delete x;
    x = nullptr;
  }
}
4

1 回答 1

1

它只对我有用...

ref class bob
{
};

ref class bill : public bob
{
};

void DeleteX( bob ^% x )
{
  if( x != nullptr )
  {
    delete x;
    x = nullptr;
  }
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    bob^ one = gcnew bill();
    DeleteX(one);
    System::Diagnostics::Trace::Assert(one == nullptr); //did not trigger
于 2009-09-29T14:22:11.520 回答