如何从不同头文件中的类继承?

Ste*_*ley 4 c++ inheritance organization

我有依赖性麻烦.我有两个班:GraphicImage.每个人都有自己的.cpp和.h文件.我将它们声明如下:

Graphic.h:


    #include "Image.h"
    class Image;
    class Graphic {
      ...
    };
Run Code Online (Sandbox Code Playgroud)

Image.h:


    #include "Graphic.h"
    class Graphic;
    class Image : public Graphic {
      ...
    };
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我收到以下错误:

    Image.h:12: error: expected class-name before ‘{’ token

如果我Graphic从我删除前向声明Image.h我得到以下错误:

    Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
    Image.h:10: error: forward declaration of ‘struct Graphic’

Cla*_*diu 10

这对我有用:

image.h的:

#ifndef IMAGE_H
#define IMAGE_H

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

};

#endif
Run Code Online (Sandbox Code Playgroud)

Graphic.h:

#ifndef GRAPHIC_H
#define GRAPHIC_H

#include "Image.h"

class Graphic {
};

#endif
Run Code Online (Sandbox Code Playgroud)

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

#include "Graphic.h"

int main()
{
  return 0;
}
Run Code Online (Sandbox Code Playgroud)


mar*_*jne 5

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