具有双重分派(dispatch)的 C++ 多态循环依赖

标签 c++ polymorphism circular-dependency double-dispatch

所以,我在循环依赖方面遇到了一个大问题。我的 Square.h 和 Circle.h 类都继承了 Shape.h,并使用双重调度来尝试检测两者之间的碰撞。我的类(class)目前以下列方式设置

形状.h

class Shape {
public:
    virtual bool detectCollision(Shape* obj) = 0;
    virtual bool detectCollision(Square* obj) = 0;
    virtual bool detectCollision(Circle* obj) = 0;

正方形.h

#include "shape.h"
class Square : public Shape {
public:
    bool detectCollision(Shape* obj);
    bool detectCollision(Square* obj);
    bool detectCollision(Circle* obj);

圆.h

#include "shape.h"
class Circle: public Shape {
public:
    bool detectCollision(Shape* obj);
    bool detectCollision(Square* obj);
    bool detectCollision(Circle* obj);

本质上我希望能够做类似的事情

Circle circle;
Square square;
Square square2;

circle.detectCollision(&square);
square.detectCollision(&square2);

但是当我尝试编译它时遇到了一些错误。显然,在 Square.h 内部包含“Circle.h”将导致无法执行的循环。有人可以针对这个问题提出一个好的解决方案吗?

显然,两个正方形与圆形和正方形之间的碰撞检测是不同的,因此我需要以某种方式重载这些方法。我认为这将是一个很好的解决方案,有什么建议吗?

错误(这些编译错误是相同的或 Square.cpp 和 Shape.cpp):

Circle.cpp
    shape.h(12): error C2061: syntax error : identifier 'Square'
    shape.h(13): error C2061: syntax error : identifier 'Circle'
    shape.h(13): error C2535: 'bool Shape::detectCollision(void)' : member function already defined or declared

最佳答案

您只需要前向声明。

class Square; // Declarations, not definitions.
class Circle;

class Shape {
    // At this point, Square * and Circle * are already well-defined types.
    // Square and Circle are incomplete classes though and cannot yet be used.

我建议使用引用而不是指针,因为 nullptr 不是一个可行的论点,并且 const 限定一切,因为碰撞检测不需要修改任何东西。

关于具有双重分派(dispatch)的 C++ 多态循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390509/

相关文章:

指向 Eigen::Map<Eigen::VectorXd> 对象的 C++ 特征指针

c++ - 如何在 C++ 中将数据插入嵌套映射?

c++ - 运算符重载嵌套在类中的枚举

Java多态方法重写

c++ - 在指针c++中如何使用继承类的实际功能

c# - 处理 EF 中循环引用的干净方法?

spring - Gradle 多模块项目 : Apply module dependency to all subprojects except for itself

node.js - 使用 requirejs 解决 Node 中的循环依赖

c++ - 在Visual C++中调试代码时获取argc为零和argv为null

c++ - 我需要帮助来理解编程挑战