1

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

形状.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);

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

2 回答 2

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由于碰撞检测不需要修改任何东西,所以对所有内容进行限定。

于 2013-12-05T03:07:42.640 回答
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;
};
于 2013-12-05T03:07:44.097 回答