zoukankan      html  css  js  c++  java
  • 两个类相互包含对方成员的问题(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 }
  • 相关阅读:
    Java语法基础-final关键字
    Java语法基础-异常处理
    Java语法基础-序列化
    Java的知识储备及面试-几个方面
    一篇分析测试开发人员的职业发展方向的好文章-学习笔记
    web 自动化测试 selenium基础到应用(目录)
    打包Scala jar 包的正确步骤
    IT项目管理
    寄存器 & 汇编指令
    Window环境下编写Shellcode(入门篇)
  • 原文地址:https://www.cnblogs.com/kevinGaoblog/p/2477669.html
Copyright © 2011-2022 走看看