向前声明生成不兼容类型错误 [英] forward declaration generates incompatible type error
问题描述
我一直在阅读一些关于远期声明,包括在这个论坛。他们都说,它保存我们从包括头文件,但下面的代码生成一个错误:
#ifndef CLASSA_H_
#define CLASSA_H_
B类;
A类{
public:
A();
〜A();
int getCount();
private:
static int _count;
int _num;
B _b1; // ERROR
};
编译器说:
Ah:23:error: _b1'有不完整的类型
我注意到,如果我使
_b1
code> B * 问题解决了。 所以前向声明只适用于指针类型吗?
如果我想要 A 持有
B
对象,我必须 #inlcudeBh / code>?
谢谢!
编译器必须知道类 B
的确切定义,以确定至少要给类 A
的大小。如果你使用一个指针,它知道它的大小。
注意循环依赖是不可能的。如果你想要
class A {B b; };
class B {A a; };
那么A和B必须有无限大小...
I've been reading some on forward declarations, including in this forum. They all say that it saves us from including the header file, However the following code generates an error:
#ifndef CLASSA_H_
#define CLASSA_H_
class B;
class A {
public:
A();
~A();
int getCount();
private:
static int _count;
int _num;
B _b1; //ERROR
};
compiler says:
A.h:23: error: field ‘_b1’ has incomplete type
I noticed that if i make _b1
of type B*
the problem is solved.
So is forward declaration good only for pointer types?
If i want A
to hold B
object i have to #inlcude "B.h"
?
thanks!
The compiler has to know the exact definition of class B
to determine at least what size to give to class A
. If you use a pointer, it knows its size.
Note that circular dependencies are not possible. If you want
class A { B b; };
class B { A a; };
then A and B must have infinite size...
这篇关于向前声明生成不兼容类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!