[C ++]エラーC2027:未定義の型が使用され、2つのクラス間の相互参照メンバー、前方宣言



Error C2027 Undefined Type Used



エラーC2027:未定義の型の使用、2つのクラス間の参照メンバー、前方宣言

独自のクラスを作成する場合、2つのクラス間の相互参照に遭遇する可能性があります
例:クラスAとクラスBが定義され、AはBによって定義されたタイプを使用し、BもAによって定義されたタイプを使用します。
  1. 2つのクラスのメソッドパラメーターとして他のクラスのみを使用する場合、または型のポインターと参照の動作を定義する場合は、前方宣言を使用できます。

    未定義の型への参照は許可されていません。
    画像
    前方宣言を使用して解決します。
    画像



  2. 前方宣言が使用された後、クラス定義の前に、クラスは競合しない型です。つまり、前方宣言されたクラスが型であることがわかっていますが、どのメンバーが含まれているかがわからないため、前方宣言を使用した後宣言、クラスを定義する前に定義できるのは型へのポインターと参照のみであり、クラスメンバーを使用することはできません

    クラス定義の前にクラスメンバーを使用することはできません
    画像



2つのクラス間の相互参照メンバーを実現するための個別のコンパイルおよび前方宣言メソッドを介して

前方宣言されたメソッドはクラスメンバーを使用できず、これがクラスタイプであることをコンパイラに知らせることしかできません。

同じプロジェクト内のC ++の異なるファイルはグローバルスコープにあり、他のファイルで参照することもできます。ある.cppが別の.cpp定義関数を使用したい場合は、この.cppファイルに関数宣言を記述してください。

異なるクラスを異なるクラスファイルに分離することにより、異なるクラスはクラス宣言とクラス定義を分離します。他のクラスを使用する必要がある場合は、ターゲットクラスのヘッダーファイル(宣言の導入)を導入することで、ターゲットクラスを使用できます。



ヘッダーファイルの宣言

#pragma once #include <iostream> #include'SeparateCompilationClass1.h'//After the compilation is complete, the preprocessor adds the content of the file to the program, and the header file has the complete declaration of class B using namespace std class B//Use forward declaration, the compiler indicates this is a class type, so that the header file declaration is compiled class A { public: void fun(B* b)//Because it is a declaration, class members are not used, and forward declarations can be compiled }

画像

ソースファイルの実装

#include'SeparateCompilationClass2.h'//The header file of class A, in which the header file of B is referenced, has the completion statement of B, so class B members can be used in this file void A::fun(B* b) {//Add member definitions for class A through the scope operator cout << 'Method in A' << endl cout << 'Use members from B:' << endl b->fun()//The members in B can be used through separate compilation }

画像