[英]Uses undefined class/has incomplete type
class a;
class b;
class a {
b c;
};
class b {
};
为什么不编译? 我的印象是,如果你宣布了类的原型,它们的声明顺序并不重要。 但是,这不起作用。 在视觉工作室,它给了我:
error C2079: 'a::c' uses undefined class 'b'
在g ++中,它给了我:
error: field 'c' has incomplete type
我究竟做错了什么?
当编译器看到
class a {
b c;
};
它知道b
存在,但它不知道它是什么(因此,它不知道它需要多少空间,因此它不知道如何建立a
)
但是你可以做的是在b
上使用指针:
class a {
b* c;
};
编辑:
这意味着您无法在定义之前操纵b
。 例如:你做不到 :
class a {
b* c;
void f(){
c->doSomething(); // <- Won't compile
}
};
你可以做的是分离.hh
和.cc
a
定义:
在a.hh
class b; //Say it exists. Don't say what it looks like
class a {
b* c;
void f();
};
在a.cc
#include "b.hh" //now it's ok to use b.hh: it won't yield a circular reference because b.hh may include a.hh but it doesn't include a.cc
void a::f(){
c->doSomething();
}
当时a
使用b
已经宣布(因为你写的class b;
其上方),但没有定义(定义为低于a
)。 “不完整类型”表示已声明但未定义的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.