我有依赖性麻烦。我有两个类: Graphic Image 。每个人都有自己的.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: error: expected class-name before ‘{’ token

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

    Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
    Image.h:10: error: forward declaration of ‘struct Graphic’
有帮助吗?

解决方案

这对我有用:

image.h的:

#ifndef IMAGE_H
#define IMAGE_H

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

};

#endif

Graphic.h:

#ifndef GRAPHIC_H
#define GRAPHIC_H

#include "Image.h"

class Graphic {
};

#endif

以下代码编译时没有错误:

#include "Graphic.h"

int main()
{
  return 0;
}

其他提示

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

Graphic.h不需要包含image.h,也不需要转发声明Image类。此外,Image.h不需要转发声明Graphic类,因为你#include定义该类的文件(如你所知)。

<代码> Graphic.h:

class Graphic {
  ...
};

<代码> image.h的

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

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

<代码> Graphic.h

class Graphic {
  ...
};

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

class Graphic;

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top