具有双重调度的C ++多态循环依赖

时间:2013-12-05 02:53:38

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

所以,我在循环依赖方面遇到了很大的问题。我的Square.h和Circle.h类都继承了Shape.h,并使用double dispatch来尝试检测两者之间的冲突。我的课程目前以下列方式设置

Shape.h

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

Square.h

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

Circle.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);

但是当我尝试编译时,我遇到了一些错误。显然包括“Circle.h”,Square.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

2 个答案:

答案 0 :(得分:4)

你只需要前瞻声明。

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 - 因为碰撞检测不需要修改任何内容而限定所有内容。

答案 1 :(得分:1)

您需要转发声明类:

class Square;
class Circle;

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