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

 1 //B.h文件
 2 #ifndef B
 3 #define B         //预处理命令中,没有包含A类的头文件,包含的话就错了
 4 class B 
 5 {
 6 public:
 7     class A * a;     //前向声明A类,同时声明A类的指针,注意,如果声明A类的对象就错了!
 8     void fun2();
 9 }; 
10 #endif
 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     B  b;        //这里和上面不同可以声明一个对象,当然也可以是指针
10     void fun1( );
11 }; 
12 #endif
 1 //B.cpp文件
 2 #include "stdafx.h"
 3 #include "A.h"
 4 #include <iostream>
 5 using std::cout;
 6 using std::endl;
 7 void B::fun2()
 8 { 
 9     cout<<"b"<<endl<<count++<<endl;
10     if(count==1000)
11     {
12         cout<<"太多了,停不下来了";
13         getchar();
14         exit(0);
15     }
16     a=new A;
17     a->fun1();
18 }
 1 //A.cpp文件
 2 #include "stdafx.h"
 3 #include "A.h"
 4 #include <iostream>
 5 using std::cout;
 6 using std::endl;
 7 void A::fun1()
 8 {
 9     cout<<"a"<<endl<<count++<<endl;
10     if(count==1000)
11     {
12         cout<<"太多了,停不下来了";
13         getchar();
14         exit(0);
15     }
1617     b.fun2();
18 }
 1 //main程序文件
 2 #include "stdafx.h"
 3 #include<iostream>
 4 #include"A.h"
 5 using std::cout;
 6 using std::endl;
 7 
 8 void main()
 9 {
10    A a;
11    B b;
12    a.fun1();
13    b.fun2();
14 
15    getchar();
16 }

posted on 2012-05-01 10:07  NLP新手  阅读(271)  评论(1编辑  收藏  举报

导航