我有两节课,class A和class B.
A.h -> A.cpp
B.h -> B.cpp
Run Code Online (Sandbox Code Playgroud)
然后,我将B设置为A类中的成员.然后,A类可以访问B类
#include <B.h>
Run Code Online (Sandbox Code Playgroud)
但是,如何在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
Run Code Online (Sandbox Code Playgroud)
只需使用前瞻声明.喜欢:
啊:
#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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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.
}
Run Code Online (Sandbox Code Playgroud)
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.
}
Run Code Online (Sandbox Code Playgroud)
知道这B is a class对于编译器定义是足够的pointer to B,无论B是什么.当然,这两个.cpp文件应该包括A.h并且B.h能够访问类成员.