两个类相互包含的处理策略

来源:互联网 发布:h248协议端口号 编辑:程序博客网 时间:2024/06/08 19:01

一、两个类相互包含的示范

A.h

/*A.h*/#ifndef __A_H__#define __A_H__#include "B.h"class A{    B* b;};#endif

B.h

/*B.h*/#ifndef __B_H__#define __B_H__#include "A.h"class B{private:    A* a;};#endif
A.cpp

#include "A.h"

B.CPP

#include "B.h"

编译命令:

g++ main.cpp A.cpp B.cpp -o main


报错:

In file included from A.h:5:0,                 from main.cpp:1:B.h:10:5: error: ‘A’ does not name a type     A* a;     ^adminer@ubuntu:~/work_space/zhangkesong/CrossLineApp/lib$ g++ main.cpp A.cpp B.cpp -o mainIn file included from A.h:5:0,                 from main.cpp:1:B.h:10:5: error: ‘A’ does not name a type     A* a;     ^In file included from A.h:5:0,                 from A.cpp:1:B.h:10:5: error: ‘A’ does not name a type     A* a;     ^In file included from B.h:5:0,                 from B.cpp:1:A.h:9:5: error: ‘B’ does not name a type     B* b;     ^

二、处理策略

处理思想:将至少其中的一个头文件放入另外一个cpp文件中。

1、用void*

/*A.h*/#ifndef __A_H__#define __A_H__class A{    public:    void Show();    void Out();    private:    void* b;};#endif

A.cpp

#include "A.h"#include <iostream>#include "B.h"void A::Show(){    std::cout<<__PRETTY_FUNCTION__<<std::endl;}void A::Out(){    std::cout<< __PRETTY_FUNCTION__<<std::endl;    ((B*)b)->Show();}

B.h

/*B.h*/#ifndef __B_H__#define __B_H__#include "A.h"class B{public:    void Show();    void Out();    private:    A* a;};#endif

B.cpp

#include "B.h"#include <iostream>void B::Show(){    std::cout<<__PRETTY_FUNCTION__<<std::endl;}void B::Out(){    std::cout<<__PRETTY_FUNCTION__<<std::endl;    a->Show();}

main.cpp

#include "A.h"#include "B.h"int main(){    A a;    a.Out();    B b;    b.Out();    return 0;}

编译命令:

g++ main.cpp A.cpp B.cpp -o main

执行结果:

void A::Out()void B::Show()void B::Out()void A::Show()

2、利用静态成员函数的特性

A.h

/*A.h*/#ifndef __A_H__#define __A_H__class A{   public:    void Show();    void Out();    static A& Itc();};#endif

A.cpp

#include "A.h"#include <iostream>#include <sys/stat.h>#include "B.h"A& A::Itc(){    static A a;    return a;}void A::Show(){    std::cout<<__PRETTY_FUNCTION__<<std::endl;}void A::Out(){    std::cout<< __PRETTY_FUNCTION__<<std::endl;    B::Itc().Show();}

B.h

/*B.h*/#ifndef __B_H__#define __B_H__class B{public:    static B& Itc();    void Show();    void Out();};#endif

B.cpp

#include "B.h"#include <iostream>#include "A.h"B& B::Itc(){    static B b;    return b;}void B::Show(){    std::cout<<__PRETTY_FUNCTION__<<std::endl;}void B::Out(){    std::cout<<__PRETTY_FUNCTION__<<std::endl;    A::Itc().Show();}

main.cpp

#include "A.h"#include "B.h"int main(){    A::Itc().Out();    B::Itc().Out();    return 0;}

编译命令:

g++ main.cpp A.cpp B.cpp -o main

执行结果:

void A::Out()void B::Show()void B::Out()void A::Show()


0 0
原创粉丝点击