【问题标题】:C++ include files confusionC++ 包含文件混淆
【发布时间】:2013-03-21 10:01:42
【问题描述】:

我正在尝试在我的 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

如您所见,圆形包括形状,其中包括 shapevisitor,同样,形状也包括圆形。

有什么想法吗?

【问题讨论】:

  • 如你所见...我一定是瞎子,我没看到。我看到的是没有包含,所以 Cyrcle 是未声明的。
  • 你的类定义需要分号。
  • 也许this 可以帮助您详细了解发生了什么

标签: c++ header include forward-declaration


【解决方案1】:

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

Herb Sutter 的这篇 ancient(但仍然非常正确!)专栏是一个很好的参考。

【讨论】:

  • @artlessnoise 感谢您详细说明前向声明是什么,补充说。但请注意,即使函数签名是void visitCircle(Circle s),也不需要标头!
  • 啊,好的,谢谢你的解释!那么我假设,在我的 Shape 类中,我也只需要“ShapeVisitor”的前向声明吗?
  • @docaholic 是正确的,但请注意,Circle.h 确实需要包含 Shape.h,因为派生类需要基类定义才能自行定义。
  • 对不起,我已经有一段时间没有用 C++ 编程了。推导或组合。
  • 感谢 rhalbersma,这确实更有意义。如果可以的话,我会两次支持你的答案!
猜你喜欢
  • 2013-12-17
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多