子类指针的转换无效
Invalid conversion of child class pointer
在以下代码中:
#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!
您可以安全地从指向派生类的指针转换为指向基类的指针,但不能安全地转换,因为您不知道所指向的对象是否具有正确的类型。
相关文章:
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- is_same和variadic模板编译时错误无效转换
- 如何将常量无效*转换为istream?
- 无效* 转换获得意外输出
- 无法确定为什么函数调用中从 char* 到 char 的无效转换
- 在这个简单函数中从'char'到'const char*'的无效转换
- C++从 'const char*' 到 'char*' Arduino Uno 的无效转换
- 如何修复C++中的"错误:从'int'到'const char*'[-fallowive]的无效转换?
- C 错误:从(基类模板)到子类的无效转换
- 如何将常量无效*转换为无符号字符*
- 函数模板中的无效转换错误,返回值取决于其泛型类型
- 常量正确性编译错误到模板函数中的无效转换错误
- 从"char"到"const char*"的无效转换[-fpermissive](idk why)
- 从“ void*”到“ pthread_t*”的无效转换
- 当函数调用时,试图阻止数组更改时发生无效转换错误
- 使用基类中定义的函数返回指向派生类实例的指针时发生无效转换错误
- C++从字符到常量字符*的无效转换
- ALL_OF从'char'到'const char*'的无效转换 [-允许]
- C和C++上的无效转换错误
- C++ 在模板专用化中从 strcmp() 中的 'char' 到 'const char*' 的无效转换