j****i 发帖数: 305 | 1 A has member object B, and B has A. It won't compile. How to fix this?
My actuall program has much more complicated dependence, and I'm using head
files etc, how to fix that?
Thanks a lot.
class A{
public:
A();
B b;
};
class B{
public:
B();
A a;
};
A::A(){}
B::B(){}
int main(){
A a();
return 0;
} |
t****t 发帖数: 6806 | 2 ask yourself, what is sizeof(A) if this is allowed?
of course it won't compile. C++ isn't java, this is not allowed. for java,
object is just a pointer (or reference); for c++, an object is really an
object.
head
【在 j****i 的大作中提到】 : A has member object B, and B has A. It won't compile. How to fix this? : My actuall program has much more complicated dependence, and I'm using head : files etc, how to fix that? : Thanks a lot. : class A{ : public: : A(); : B b; : }; : class B{
|
j****i 发帖数: 305 | 3 Thanks. How do I get around this? Define a parent class of A that does not c
ontain B? I really have no clue.
【在 t****t 的大作中提到】 : ask yourself, what is sizeof(A) if this is allowed? : of course it won't compile. C++ isn't java, this is not allowed. for java, : object is just a pointer (or reference); for c++, an object is really an : object. : : head
|
t****t 发帖数: 6806 | 4 use pointers to refer each other.
c
【在 j****i 的大作中提到】 : Thanks. How do I get around this? Define a parent class of A that does not c : ontain B? I really have no clue.
|
j****i 发帖数: 305 | 5 You mean void* pointers? If I replace B b; by B* b, it still does not work.
【在 t****t 的大作中提到】 : use pointers to refer each other. : : c
|
t****t 发帖数: 6806 | 6 write
class B;
before you define A. that's called forward declaration (google it if you don
't know what to do)
【在 j****i 的大作中提到】 : You mean void* pointers? If I replace B b; by B* b, it still does not work.
|
j****i 发帖数: 305 | 7 Yeah, that works. Thanks.
don
【在 t****t 的大作中提到】 : write : class B; : before you define A. that's called forward declaration (google it if you don : 't know what to do)
|