【发布时间】:2012-12-29 16:40:06
【问题描述】:
我正在尝试使用来自here 的信息在班级之间共享信息, 除了我无法编译这两个类,因此 相互交流。
所以,我想要ClassB 获得对ClassA 的引用,并且
ClassB 将在 ClassA 中初始化。
编译器错误(使用 g++):
在成员函数
'void ClassA::foo()':
hello.cpp:9: 错误:'ClassB'未在此范围内声明
hello.cpp:9: 错误:'someB'未在此范围内声明
hello.cpp:9:错误:'ClassB'之前的预期类型说明符
hello.cpp:9: 错误:在'ClassB'之前应为';'
然后我尝试在ClassA 之前添加class ClassB;,
喜欢:
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”的前向声明
hello.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();
}
};
【问题讨论】:
-
请查一下继承这个词。您可能会发现它很有用。
-
这里不能使用继承,因为我在处理对象,一个实例化类的引用,所以我不能继承对象引用。
-
构造函数在哪里?