5

我有依赖问题。我有两个班级:GraphicImage。每个都有自己的 .cpp 和 .h 文件。我将它们声明如下:

Graphic.h


    #include "Image.h"
    class Image;
    class Graphic {
      ...
    };

Image.h


    #include "Graphic.h"
    class Graphic;
    class Image : public Graphic {
      ...
    };

当我尝试编译时,出现以下错误:

    Image.h:12:错误:“{”标记之前的预期类名

如果我删除Graphicfrom的前向声明,Image.h则会收到以下错误:

    Image.h:13:错误:不完整类型“结构图形”的无效使用
    Image.h:10:错误:“结构图形”的前向声明
4

5 回答 5

12

这对我有用:

图片.h:

#ifndef IMAGE_H
#define IMAGE_H

#include "Graphic.h"
class Image : public Graphic {

};

#endif

图形.h:

#ifndef GRAPHIC_H
#define GRAPHIC_H

#include "Image.h"

class Graphic {
};

#endif

以下代码编译没有错误:

#include "Graphic.h"

int main()
{
  return 0;
}
于 2008-10-31T12:27:37.127 回答
5

您不需要在 Graphic.h 中包含 Image.h 或转发声明 Image - 这是一个循环依赖。如果 Graphic.h 依赖于 Image.h 中的任何内容,则需要将其拆分为第三个标头。(如果 Graphic 有一个 Image 成员,那就行不通了。)

于 2008-10-31T12:14:02.427 回答
4

Graphic.h 不需要包含 image.h,也不需要转发声明 Image 类。此外, Image.h 不需要转发声明 Graphic 类,因为您 #include 定义该类的文件(您必须这样做)。

Graphic.h:

class Graphic {
  ...
};

Image.h

#include "Graphic.h"
class Image : public Graphic {
  ...
};
于 2008-10-31T12:31:28.320 回答
1

由于 Image 扩展了 Graphic,因此请删除 Graphic.h 文件中包含的 Image。

Graphic.h

class Graphic {
  ...
};
于 2008-10-31T12:14:37.013 回答
0

首先删除它,您必须始终拥有完整的类定义才能从类继承:

class Graphic;

其次,从 Graphic.h 中删除所有对 Image 的引用。父母通常不需要知道它的孩子。

于 2008-10-31T12:15:18.963 回答