此代码有什么问题? 在这里,我们有两个文件:classA.h和classB.hC++中的相互类实例
classA.h:
#ifndef _class_a_h_
#define _class_a_h_
#include "classB.h"
class B; //????
class A
{
public:
A() {
ptr_b = new B(); //????
}
virtual ~A() {
if(ptr_b) delete ptr_b; //????
num_a = 0;
}
int num_a;
B* ptr_b; //????
};
#endif //_class_a_h_
classB.h:
#ifndef _class_b_h_
#define _class_b_h_
#include "classA.h"
class A; //????
class B
{
public:
B() {
ptr_a = new A(); //????
num_b = 0;
}
virtual ~B() {
if(ptr_a) delete ptr_a; //????
}
int num_b;
A* ptr_a; //????
};
#endif //_class_b_h_
当我尝试编译,编译器(g ++)说:
classB.h: In constructor ‘B::B()’:
classB.h:12: error: invalid use of incomplete type ‘struct A’
classB.h:6: error: forward declaration of ‘struct A’
classB.h: In destructor ‘virtual B::~B()’:
classB.h:16: warning: possible problem detected in invocation of delete operator:
classB.h:16: warning: invalid use of incomplete type ‘struct A’
classB.h:6: warning: forward declaration of ‘struct A’
classB.h:16: note: neither the destructor nor the class-specific operator delete will be
called, even if they are declared when the class is defined.
每当类此耦合的,您的设计可能需要一些重构前摆好完成。 – GManNickG 2010-03-30 01:52:22
@GMan:与实施迭代器模式的一个例外,非常同意。 +1。 – 2010-03-30 01:53:29