2012-01-30 8 views
0

私は2つのクラス、class Aclass Bを持っています。C++では、2つのクラスが互いにアクセスするようにします

A.h -> A.cpp 
B.h -> B.cpp 

そして、私は、クラスAのメンバーとしてBを設定し、クラスAは

#include <B.h> 

によってクラスBにアクセスすることができます。しかし、どのように私は、クラスBのクラスAのポインタを取得することができますクラスAのパブリックメンバーにアクセスできますか?

私はインターネットに関するいくつかの情報を見つけました:クロスクラス。クラスBをクラスAのネストされたクラスとして設定することができると述べた。

他にアドバイスはありますか?

申し訳ありません。 myCode:従うよう..

class A: 

#ifndef A 
#define A 

#include "B.h" 

class A 
{ 
public: 
    A() { 
     b = new B(this); 
    } 

private: 
    B* b; 
}; 

#endif 


#ifndef B 
#define B 

#include"A.h" 

class B 
{ 
public: 
    B(A* parent = 0) { 
     this->parent = parent; 
    } 

private: 
    A* parent; 
}; 

#endif 
+0

あなたは最終的に達成しようとしていますか? – wilhelmtell

+4

関連コードを投稿してください。 –

+0

2回目は 'A'ではなく' class B'と読むべきでしょうか?さもなければ、それはとにかく再定義、すなわちエラーです。 – vines

答えて

6

ちょうどforward declarationを使用しています。同様に:

A.h:

#ifndef A_h 
#define A_h 

class B; // B forward-declaration 

class A // A definition 
{ 
public: 
    B * pb; // legal, we don't need B's definition to declare a pointer to B 
    B b; // illegal! B is an incomplete type here 
    void method(); 
}; 

#endif 

B.h:

#ifndef B_h 
#define B_h 

#include "A.h" // including definition of A 

class B // definition of B 
{ 
public: 
    A * pa; // legal, pointer is always a pointer 
    A a; // legal too, since we've included A's *definition* already 
    void method(); 
}; 

#endif 

A.cpp

#inlude "A.h" 
#incude "B.h" 

A::method() 
{ 
    pb->method(); // we've included the definition of B already, 
        // and now we can access its members via the pointer. 
} 

B.cpp

#inlude "A.h" 
#incude "B.h" 

B::method() 
{ 
    pa->method(); // we've included the definition of A already 
    a.method(); // ...or like this, if we want B to own an instance of A, 
        // rather than just refer to it by a pointer. 
} 

B is a classを知っていれば、コンパイラはpointer to Bを定義するのに十分です。Bです。もちろん、.cppのファイルには、クラスメンバーにアクセスできるように、A.hB.hのファイルを含める必要があります。

+0

ありがとうございます。しかし、私はクラスAのクラスBにアクセスしますか?どのようにできるのか ? –

+0

'.cpp'ファイルでは、両方のヘッダーをインクルードし、両方のクラスのメンバーにアクセスすることができます。ヘッダーには、一般的にそれらにアクセスすべきではありません。 – vines

+0

もし私がそれをやらなければならないと、クラスAのネストされたクラスとしてクラスBを作ることができますか?私はそれを作る...しかし、私はプロジェクトを作る:mainWindow演算子とこれのようなメンバオブジェクトがたくさんある、私はmainWindowのメンバオブジェクトにアクセスし、メンバオブジェクトのmainWindowのポインタを取得し、 mainWindow public functionにアクセスしてください..私はそれが非常に厄介だと思う...あなたはそれを作る方法を持っていますか? –

関連する問題