0

両方のオブジェクト (二重にリンクされた子と親) 内で子オブジェクトと親オブジェクトを適切に参照するにはどうすればよいですか? これを行うと、コンパイル エラーが発生します: **** does not name a type. #define タグが原因で #include ステートメントが省略されていることに関係していると思われます。したがって、これらのタグをどのように含める必要がありますか?

次のように記述された 3 つのファイル (Parent.h、Child.h、main.cpp):

    /* Parent.h */
#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

#include "Child.h"

class Parent {
public:
    Parent() {}
    ~Parent() {}
    void do_parent(Child* arg);
};
#endif

/* Child.h */
#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

#include "Parent.h"

class Child {
public:
    Child() {}
    ~Child() {}
    void do_child(Parent* arg);
};
#endif

/* main.cpp */
#include "child.h"
#include "parent.h"

int main()
{
    Child   a();
    Parent  b();
    a.do_parent(Child& arg);
    return 0;
}
4

5 に答える 5

1

オブジェクトの代わりに 2 つの関数を定義しました。最も面倒な解析を参照してください

アップデート

Child   a();              // a is a function returns Child object
Parent  b();              // b is a function returns Parent object
a.do_parent(Child& arg);

Child   a;           // a is a Child object
Parent  b;           // b is a Parent object
b.do_parent(&a);

また、循環インクルードの問題があります。循環インクルードを解除するには、1 つのタイプを転送する必要があります。

Child.h

#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

//#include "Parent.h"  Don't include Parent.h
class Parent;           // forward declaration
class Child {
public:
    Child() {}
    ~Child() {}
    void do_child(Parent* arg);
};
#endif

チャイルド.cpp

#include "Parent.h"
// blah
于 2013-02-11T09:02:06.700 に答える
1

ヘッダー ファイルの循環依存関係があります。ヘッダーの 1 つでいずれかのクラスを宣言するだけです。例えば:

    /* Parent.h */
#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

//#include "Child.h"   ----> Remove it
class Child;           //Forward declare it

class Parent {
public:
    Parent() {}
    ~Parent() {}
    void do_parent(Child* arg);
};
#endif
于 2013-02-11T09:00:39.970 に答える
1

クラス プロトタイプ / 前方宣言を使用します。

class Child;

class Parent;

お互いのクラス宣言の前にインクルードを削除します。

于 2013-02-11T09:01:07.683 に答える
0

orの前方宣言が必要です。ファイルの 1 つを変更してみてください。class Parentclass Child

あなたのParent.hで:

#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

class Child;     // Forward declaration of class Child

class Parent {
public:
    Parent() {}
    ~Parent() {}
    void do_parent(Child* arg);
};
#endif

またはあなたの Child.h で:

#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

class Parent;    // Forward declaration of class Parent

class Child {
public:
    Child() {}
    ~Child() {}
    void do_child(Parent* arg);
};
#endif

この質問はあなたに大いに役立つはずです。

于 2013-02-11T09:02:42.230 に答える
0

エラーは、次の行だと思います (コンパイル/リンカー エラーについて尋ねるときは、常に完全未編集のエラー メッセージを含める必要があります)。

a.do_parent(Child& arg);

Childここでは、変数宣言ではなく、オブジェクトへのポインターを渡す必要があります。

b.do_parent(&a);
于 2013-02-11T09:01:42.163 に答える