別のヘッダーファイルのクラスからどのように継承しますか?
-
05-07-2019 - |
質問
依存関係に問題があります。 Graphic
と Image
の2つのクラスがあります。それぞれに独自の.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;
}
他のヒント
Image.hを含めたり、Graphic.hで前方宣言Imageする必要はありません。これは循環依存関係です。 Graphic.hがImage.hの何かに依存している場合、それを3番目のヘッダーに分割する必要があります。 (GraphicにImageメンバーがある場合、それは機能しません。)
Graphic.hにはimage.hを含める必要はなく、Imageクラスを前方宣言する必要もありません。また、Image.hは、そのクラスを定義するファイルを#includeするので(必要に応じて)Graphicクラスを前方宣言する必要がありません。
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へのすべての参照を削除します。通常、親は子を知る必要はありません。
所属していません StackOverflow