在C ++中,我希望两个类可以相互访问

时间:2012-01-30 05:37:30

标签: c++

我有两个课程,class Aclass B

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

然后,我将B设置为A类中的成员。然后,A类可以通过

访问B类
#include <B.h>   

但是,如何在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

1 个答案:

答案 0 :(得分:7)

只需使用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才能访问类成员。