简体   繁体   English

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

[英]In C++, I want two classes to access each other

I have two classes, class A and class B . 我有两个班级, class A class Bclass B

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

And then, I set B as a member in class A. Then, class A can access class B by 然后,我将B设置为A类的成员。然后,A类可以通过以下方式访问B类:

#include <B.h>   

But, how can I get the pointer of class A in class B and access the public member of class A? 但是,如何获取B类中A类的指针并访问A类的公共成员?

I found some information about on the internet: a Cross-class. 我在互联网上找到了一些信息:跨班。 They said you can make it by setting the class B as a nested class in class A. 他们说可以通过将B类设置为A类中的嵌套类来实现。

Do you have any other advice? 您还有其他建议吗?

sorry. 抱歉。 myCode: as follow.. 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

Just use forward declaration . 只需使用前向声明 Like: 喜欢:

Ah: 啊:

#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

Bh: Bh:

#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.
}

Knowing that B is a class is enough for compiler to define pointer to B , whatever B is. 知道B is a class就足以使编译器定义pointer to B ,无论B是什么。 Of course, both .cpp files should include Ah and Bh to be able to access class members. 当然,两个.cpp文件都应包含AhBh以便能够访问类成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM