首页 > 解决方案 > 将父母作为孩子传递给函数c ++

问题描述

BoxCollider、CillinderCollider 和 PlaneCollider 都是公开的:Collider,所以我做错了什么还是这在 C++ 中根本不可能?

在此处输入图像描述

这是代码:

class Collider
{
public:
    Collider();
    ~Collider();

    std::string* checkCollision(Collider* _reference);
    char* type;
    std::string* tag;

protected:
    virtual bool checkBox(BoxCollider* _reference);
    virtual bool checkPlane(PlaneCollider* _reference);
    virtual bool checkCilinder(CillinderCollider* _reference);
};

class BoxCollider : public Collider
{
public:
    BoxCollider();
    ~BoxCollider();

private:
    virtual bool checkBox(BoxCollider* _reference);
    virtual bool checkPlane(PlaneCollider* _reference);
    virtual bool checkCilinder(CillinderCollider* _reference);
};

这是给我错误的功能:

std::string* Collider::checkCollision(Collider* _reference)
{
    bool collided;

    switch (*_reference->type)
    {
    case BOX: collided = checkBox(_reference); break;
    case CILINDER: collided = checkCilinder(_reference); break;
    case PLANE: collided = checkPlane(_reference); break;

    default: std::cout << "invalid collision type\n"; exit(0);
    }

    if (collided) { return _reference->tag; }
    return NULL;
}

标签: c++classinheritance

解决方案


作为传统继承(似乎只用于允许多次调度)的替代方案,您可以使用std::variant

// Your shape structures
struct Box
{
// center, dimension, direction...
};

struct Plan
{
// origin, vector_x, vector_y...
};

struct Cylinder
{
// origin, radius, vector_height...
};

// The real collision functions
bool checkCollision(const Box&, const Box&);
bool checkCollision(const Box&, const Plan&);
bool checkCollision(const Box&, const Cylinder&);

bool checkCollision(const Plan& plan, const Box& box) { return checkCollision(box, plan); }
bool checkCollision(const Plan&, const Plan&);
bool checkCollision(const Plan&, const Cylinder&);

bool checkCollision(const Cylinder& cylinder, const Box& box)  { return checkCollision(box, cylinder); }
bool checkCollision(const Cylinder& cylinder, const Plan& plan)  { return checkCollision(plan, cylinder); }
bool checkCollision(const Cylinder&, const Cylinder&);

// The dispatch:
using Shape = std::variant<Box, Plan, Cylinder>;

bool checkCollision(const Shape& shape1, const Shape& shape2)
{
    return std::visit([](const auto& lhs, const auto& rhs){ return checkCollision(lhs, rhs); }, shape1, shape2);
}

推荐阅读