两个类相互包含对方成员的问题(2)

 1 //A.h文件
 2 #ifndef A
 3 #define A
 4 #include"B.h"
 5 static int count=0;
 6 class A
 7 { 
 8 public:
 9     void fun1( );
10 }; 
11 #endif
12 
13 //B.h文件
14 #ifndef B
15 #define B  
16 class A;            //注意:这里是C++类的前向声明,没有用include“A.h”把对方加进来是考虑到了没有必要,因为最终两个类是要编译到一块
17 class B 
18 {
19 public:
20     void fun2();
21 }; 
22 #endif
23 
24 //A.cpp文件
25 #include "stdafx.h"
26 #include "A.h"
27 #include <iostream>
28 using std::cout;
29 using std::endl;
30 void A::fun1()
31 {
32     cout<<"a"<<endl<<count++<<endl;
33     if(count==1000)
34     {
35         cout<<"太多了,停不下来了";
36         getchar();
37         exit(0);
38     }
39     B b;
40     b.fun2();
41 }
42 
43 //B.cpp文件
44 #include "stdafx.h"
45 #include "A.h"        //注意:这个地方没用B.h是考虑到了编译连接的顺序
46 #include <iostream>
47 using std::cout;
48 using std::endl;
49 void B::fun2()
50 { 
51     cout<<"b"<<endl<<count++<<endl;
52     if(count==1000)
53     {
54         cout<<"太多了,停不下来了";
55         getchar();
56         exit(0);
57     }
58     A a;
59     a.fun1();
60 }
61 
62 
63 //main程序文件
64 #include "stdafx.h"
65 #include<iostream>
66 #include"A.h"        //注意:这个地方没有include“B.h”但是下面用的了B类,说明B类头文件肯定在A.h中有include。
67 using std::cout;
68 using std::endl;
69 void main()
70 {
71    A a;
72    B b;
73    a.fun1();
74    b.fun2();
75    getchar();
76 }
原文地址:https://www.cnblogs.com/kevinGaoblog/p/2471936.html