在C ++中,我想要两个类来访问对方 [英] In C++, I want two classes to access each other

查看:160
本文介绍了在C ++中,我想要两个类来访问对方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类, A类 B类

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

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

And then, I set B as a member in class A. Then, class A can access class B by

#include <B.h>   

但是,如何获取类B中的类A的指针并访问类的public成员A?

But, how can I get the pointer of class A in class B and access the public member of class A?

我在互联网上找到了一些信息:一个跨类。他们说你可以通过将类B设置为类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.

你有其他建议吗?

对不起。
myCode:as follows ..

sorry. myCode: as follow..

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


推荐答案

请使用转发声明。喜欢:

啊:

#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:

#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是一个类足以让编译器定义指向B 的指针,无论 B 是什么。当然, .cpp 文件应包括 Ah Bh 能够访问类成员。

Knowing that B is a class is enough for compiler to define pointer to B, whatever B is. Of course, both .cpp files should include A.h and B.h to be able to access class members.

这篇关于在C ++中,我想要两个类来访问对方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆