我正在尝试使用此处的信息在类之间共享信息,但我无法让这两个类编译并因此相互通信。
所以,我想要的是ClassB获得对 的引用ClassA,并
ClassB在ClassA.
编译器错误(使用 g++):
在成员函数中
'void ClassA::foo()':
hello.cpp:9:错误:'ClassB'未在此范围内声明
hello.cpp:9:错误:'someB'未在此范围内声明hello.cpp:9:错误: hello.cpp:9
之前的预期类型说明符'ClassB'
: 错误:';'之前预期'ClassB'
所以我尝试class ClassB;在之前添加ClassA,
喜欢:
class ClassB; // just this here.
class ClassA; // all of classA here.
class ClassB; // all of classB here.
我得到:
hello.cpp:在成员函数'void ClassA::foo()'中:
hello.cpp:11:错误:无效使用不完整类型'struct ClassB'
hello.cpp:3:错误:'struct ClassB'的前向声明
你好.cpp:12:错误:不完整类型“struct ClassB”的无效使用
hello.cpp:3:错误:“struct ClassB”的前向声明
这是我根据上面的网站尝试使用的代码:
include stdio.h
class ClassA {
public:
void foo() {
ClassB *someB = new ClassB();
someB->setRelative(this);
}
void bar() {
printf("B is communicating with me =)\n");
}
};
class ClassB {
ClassA *m_relative;
public:
void setRelative(ClassA *other) {
this->m_relative = other;
}
void foo() {
m_relative->bar();
}
};