此代碼有什麼問題? 在這裏,我們有兩個文件: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