C++包含文件混乱

doc*_*lic 2 c++ header include forward-declaration

我试图在我的c ++程序中包含文件,但我一直遇到错误:

ShapeVisitor.h:9:28: error: ‘Circle’ has not been declared

我认为问题在于类的结构方式,它导致循环依赖.我该如何解决这个问题?

类标题如下......

 //Circle.h
 #ifndef CIRCLE_H
 #define CIRCLE_H
 // headers, ...
 #include "Shape.h"
class Circle: public Shape { 
//class declaration 
}
#endif

//Shape.h
#ifndef SHAPE_H
#define SHAPE_H
// headers, ...
#include <iostream>

class Shape {  
//a certain method in the class declaration looks like this
virtual void accept(ShapeVisitor& v) = 0; 
//rest of class
}
#endif

//ShapeVisitor.h
#ifndef SHAPEVISITOR_H
#define SHAPEVISITOR_H
#include "Circle.h"
class ShapeVisitor {
//a method in the class looks like this:
virtual void visitCircle(Circle *s) = 0;
//rest of class
}
#endif
Run Code Online (Sandbox Code Playgroud)

如您所见,圆形包括形状,其中包括形状访问者,其中包括圆形.

有任何想法吗?

Tem*_*Rex 5

ShapeVisitor.h不需要包含Circle.h,前向声明class Circle;也可以.函数声明不需要它们的参数和返回类型的完整定义(即使返回/参数是值,也不需要!).只有函数的实现文件(在您的情况下:ShapeVisitor.cpp)才需要包含Circle.h.

Herb Sutter 这个古老的(但仍然非常真实!)专栏是一个很好的参考.