(一)、假如两个类class A和class B,A聚合(组合)B,B又依赖A,那么该怎么来实现呢?
那么可行的方案:
将类A的声明放在A.h,并在类A前加上一句class B;(类的一种声明方法),这样就能在类A中定义类B的指针或引用(但不能实例化和使用类B的成员及方法),类B的声明放在B.h,并在类B前加上一句class A;,这样就能在类B中定义类A的指针或引用;具体定义分别放到A.CPP和B.CPP中,在两个源文件中都包含A.h和B.h,这样各自的方法中就能使用对方类中的成员和方法了。以下是代码示例:
//A.h
#ifndef __A_h__
#define __A_h__
class B;
class A
{
public:
A(void);
~A(void);
void funcPrint();
void funcCall();
B *b;
};
#endif
//B.h
#ifndef __B_h__
#define __B_h__
class A;
class B
{
public:
void func(A *a);
};
#endif
//A.cpp
#include "A.h"
#include "B.h"
#include <iostream>
A::A(void){b = new B;}
A::~A(void){delete b;}
void A::funcPrint(){
std::cout <<"test"<<std::endl;
}
void A::funcCall(){
b->func(this);
}
//B.cpp
#include "A.h"
#include "B.h"
void B::func(A *a){
a->funcPrint();
}
忌:
假如,A.h中包含了#include "B.h",那么我们不能在B.h中包含#inlcude "A.h",这样会造成包含循环(和重复包含不同,使用了头文件卫士保护也没法避免),编译器将识别不了两个类的声明。
(二)、在(一)的的需求再加上,要把类里面方法定义为内联方法(内联类方法,有两种实现方法,但都要求声明和定义放在同一个文件中),那意味着我们不能将类的声明和定义分别放在两个不同的文件中(分开的话,编译器是不允许的),那么该怎么来实现呢?
可行方案①:
将类A和类B的定义和实现都放在一个文件C.h,以下是代码示例:
//C.h
#include <iostream>
class B;
class A
{
public:
A(void);
~A(void);
void funcPrint();
void funcCall();
B *b;
};
class B
{
public:
void func(A *a);
};
A::A(void){b = new B;}
A::~A(void){delete b;}
inline void A::funcPrint(){
std::cout <<"test"<<std::endl;
}
inline void A::funcCall(){
b->func(this);
}
inline void B::func(A *a){
a->funcPrint();
}
可行方案②:
方案①一般针对类位于同一个层次上。如果类有明显的层次关系,那么可以在一个类的声明中内嵌另一个类的声明(即将一个类作为另一个类的内嵌类)(没有层次关系当然也能这么用),以下是代码示例:
/C.h
#include <iostream>
class A
{
public:
class B
{
public:
void func(A *a){
a->funcPrint();
}
};
A(void){b = new B;}
~A(void){delete b;}
void funcPrint(){
std::cout <<"test"<<std::endl;
}
void funcCall(){
b->func(this);
}
B *b;
};
下面提供一个代码测试函数,对上面的代码都适用:
//test.cpp
#include "A.h"
//#include "C.h"
#include "stdlib.h"
int main()
{
A a;
a.funcCall();
system("pause");
return 0;
}