子类指针的转换无效

Invalid conversion of child class pointer

本文关键字:无效 转换 指针 子类      更新时间:2023-10-16

在以下代码中:

#include "itkImage.h"
#include "itkImageRegionIterator.h"
struct CustomImageBase
{
  virtual void DoSomething() = 0;
};
template <typename TPixel>
struct CustomImage : public itk::Image<TPixel, 2>, public CustomImageBase
{
  void DoSomething()
  {
    itk::Index<2> index;
    index.Fill(0);
    std::cout << this->GetPixel(index);
  }
};
int main(int, char *[])
{
  std::vector<CustomImageBase*> images;
  CustomImage<float>* floatImage = CustomImage<float>::New().GetPointer();
  CustomImage<int>* intImage = CustomImage<int>::New().GetPointer();
  return EXIT_SUCCESS;
}

我得到错误:从itk::Image*到CustomImage*的转换无效

注意,这很好用:

itk::Image<float>* testFloatImage = itk::Image<float>::New().GetPointer();

由于CustomImage继承自itk::Image,我不明白问题是什么?

如果B派生自A,则无法将A*转换为B*。如果C也派生自A,并且您的A*真的指向C对象而不是B对象,那么如果您假装它是B,会发生什么?转换不安全。在您的情况下,知道GetPointer()将始终返回CustomImage<T>。编译器不知道。你可以通过投射来判断:

CustomImage<float>* floatImage = static_cast<CustomImage<float>*>(CustomImage<float>::New().GetPointer());

编辑:这正是转换不安全的原因:在阅读了对您问题的评论后,我不认为CustomImage<float>::New().GetPointer()真的指向CustomImage,如果不是,转换只会将编译器错误转化为运行时错误。

由于CustomImage继承自itk::Image,我不明白问题是什么?

由于CustomImage继承自itk::Image,这意味着CustomImage*可以隐式转换为itk::Image*。然而,编译器抱怨相反的转换:

itk::Image*CustomImage* 的无效转换

这需要显式类型转换。

我无法编译你的代码,因为我没有先决条件,而且你也没有说编译器不喜欢哪行代码,所以在这一点上很难提供进一步的帮助。

假设这是允许的。现在考虑以下内容:

struct yet_another_image : public itk::Image<TPixel, 2> {
}
yet_another_image img;
itk::Image<TPixel, 2>* ptr = &img; // ok
CustomImage* bad = ptr; // oops!

您可以安全地从指向派生类的指针转换为指向基类的指针,但不能安全地转换,因为您不知道所指向的对象是否具有正确的类型。