C++方法声明、类定义问题
我有2个类:A和B。A类的一些方法需要使用B类,相反(B类有需要使用A类的方法)。
所以我有:
class A;
class B {
method1(A a) {
}
}
class A {
method1(B b) {
}
void foo() {
}
}
一切正常。
但是,当我尝试像这样从 B::method1 调用 A 类的 foo() 时:
class B {
method1(A a) {
a.foo();
}
}
我得到的结果是前向声明和使用不完整类型的编译错误。 但为什么会出现这种情况呢? (我在使用之前已经声明了A类?)
I have 2 classes: A and B. Some methods of class A need to use class B and the opposite(class B has methods that need to use class A).
So I have:
class A;
class B {
method1(A a) {
}
}
class A {
method1(B b) {
}
void foo() {
}
}
and everything works fine.
But when I try to call foo() of class A from B::method1 like this:
class B {
method1(A a) {
a.foo();
}
}
I get as result compile errors of forward declaration and use of incomplete type.
But why is this happening? (I have declared class A before using it?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您调用
A::foo()
时,编译器尚未看到A
的定义。您不能调用不完整类型的方法 - 即编译器尚不知道其定义的类型。您需要在编译器可以看到类A
的定义之后定义调用方法。在实践中,您可能希望将
B::method1()
的定义放在单独的cpp
文件中,其中包含一个#include
包含class A
的头文件。The compiler hasn't seen the definition of
A
at the point where you callA::foo()
. You can't call a method for an incomplete type - i.e. a type for which the compiler doesn't yet know the definition of. You need to define the calling method after the compiler can see the definition ofclass A
.In practice, you may want to place the definition for
B::method1()
in a separatecpp
file, which has an#include
for the header file containingclass A
.C++ INCLUDE 规则:尽可能使用前向声明。
B 仅使用对 A 的引用或指针。然后使用前向声明:您不需要包含。这反过来会加快编译速度。
B 派生自 A 或 B 显式(或隐式)使用 A 类的对象。然后您需要包含
来源:http://www-subatech .in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml
为了避免多次包含头文件,您应该包含一个防护,以防止编译器多次读取定义:
请参阅工业强度 C++ 第二章:组织代码。
C++ INCLUDE Rule : Use forward declaration when possible.
B only uses references or pointers to A. Use forward declaration then : you don't need to include . This will in turn speed a little bit the compilation.
B derives from A or B explicitely (or implicitely) uses objects of class A. You then need to include
Source: http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml
For avoiding multiple inclusion of header files you should include a guard, to prevent the compiler from reading the definitions more that once:
See Industrial Strength C++ Chapter Two: Organizing the code.