所以,我在循环依赖方面遇到了一个大问题。我的 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/