微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法将派生类引用作为参数的函数分配给将基类引用作为参数的函数指针

如何解决无法将派生类引用作为参数的函数分配给将基类引用作为参数的函数指针

嗨,我正在尝试创建函数指针,它需要两个对基类的引用并为其分配函数,它需要两个对派生类的引用。

假设我已经创建了函数指针

typedef bool(*MOT_fptr)(const ColliderMesh::Mesh&,const ColliderMesh::Mesh&)

然后我有函数,它返回指向所选函数函数指针

MOT_fptr GetMOT(ColliderMesh::Type type)
{
    switch (type) 
    {
        case ColliderMesh::Type::Rectangle: 
            return &Collider::BoxOverlapTest; // error: return value type does not match the function type

        case ColliderMesh::Type::Circle:  
            return &Collider::CircleOverlapTest; // error: return value type does not match the function type

        default: 
            return UNDEF_PTR; 
    }
}

其中函数 BoxOverlapTestCircleOverlapTest 被声明为

static bool BoxOverlapTest(const ColliderMesh::Rectangle& rect1,const ColliderMesh::Rectangle& rect2);
static bool CircleOverlapTest(const ColliderMesh::Circle& circ1,const ColliderMesh::Circle& circ2);

ColliderMesh::RectangleColliderMesh::Circle 均派生自基类 ColliderMesh::Mesh。但是我在返回 &Collider::BoxOverlapTest&Collider::Circle 时出现编译错误,表示 return value type does not match the function type

所以问题是..这甚至可能是我想要实现的目标而只是遗漏了一些东西,还是应该寻找其他解决方案?

解决方法

我解决了这个问题。那时我没想到我可以将函数 BoxOverlapTestCircleOverlapTest 参数声明为对基 Mesh 类的引用

所以我将这些函数声明为

static bool BoxOverlapTest(const ColliderMesh::Mesh& rect1,const ColliderMesh::Mesh& rect2);
static bool CircleOverlapTest(const ColliderMesh::Mesh& circ1,const ColliderMesh::Mesh& circ2);

然后当我调用我的函数并向它传递参数时,我只是显式地将它们强制转换为基类

auto MOTFunction = Collider::GetMOT(col1MT);
... my code ...
MOTFunction((ColliderMesh::Mesh)col1.m_Mesh[i],(ColliderMesh::Mesh)col2.m_Mesh[j]); // explicitly casting them

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。