两个类相互包含对方成员的问题(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 }

转载于:https://www.cnblogs.com/kevinGaoblog/archive/2012/05/01/2477669.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值