具有双调度的C ++多态循环依赖关系 [英] C++ Polymorphic Circular depenencies with double dispatch
问题描述
因此,我在循环依赖方面遇到了一个大问题.我的Square.h和Circle.h类都继承Shape.h,并使用double dispatch来尝试检测两者之间的冲突.目前,我的课程以以下几种方式设置
So, I'm having a big issue with circular dependency. My Square.h and Circle.h classes both inherit Shape.h, and use double dispatch in order to try and detect collision between the two. My classes are currently setup in the following sort of fashion
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);
本质上,我希望能够做类似的事情
Essentially i'm wanting to be able to do something similar to
Circle circle;
Square square;
Square square2;
circle.detectCollision(&square);
square.detectCollision(&square2);
但是当我尝试编译它时,我遇到了一些错误.显然包括Square.h在内的"Circle.h"将导致无法执行的循环.有人可以为这个问题提出一个好的解决方案吗?
But i'm running into a few errors when I try to compile this. Obviously including "Circle.h", inside of Square.h is going to cause a circular loop that won't execute. Can anybody suggest a good solution for this issue?
显然,两个正方形与一个圆和一个正方形之间的碰撞检测是不同的,因此我需要以某种方式重载那些方法.我认为这将是一个很好的解决方案,可以使用任何指针吗?
Obviously collision detection between two squares and a circle and a square is different, so I need to somehow overload those methods. I thought this would be a good solution, any pointers?
错误(这些编译错误与Square.cpp和Shape.cpp相同):
Errors (These compile errors are the same or Square.cpp and 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
推荐答案
您只需要转发声明即可.
You simply need forward declarations.
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
限定所有内容.
I would suggest using references instead of pointers, since nullptr
is not a viable argument, and const
-qualifying everything since collision detection does not require modifying anything.
这篇关于具有双调度的C ++多态循环依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!