c++ - 将父母作为孩子传递给函数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;
}
解决方案
作为传统继承(似乎只用于允许多次调度)的替代方案,您可以使用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);
}
推荐阅读
- javascript - 在Angular中的指令属性元素之外单击时将样式应用于元素
- sql - 遍历第二个表的行以返回具有累积总和的结果集
- c# - 执行 dotnet pack 时,清单错误中缺少必需的元素“元数据”
- r - 我想修复我的函数的行为
- reporting-services - SSRS 2016 数据驱动订阅未输出文件
- javascript - 单击处理程序无法频繁重新加载 div
- php - 为什么 str_getcsv() 会在字段中去除引号?
- r - 如何根据另一列中的特定日期和级别为列分配级别?
- php - 运行 Powershell 脚本后 PHP Web 应用程序响应时间长
- asp.net - 我可以在不更改代码或连接字符串的情况下强制 ASP.NET Web 应用程序池或重用连接吗?