1. 程式人生 > >c++兩個類相互調用

c++兩個類相互調用

splay ostream () inf 文件 結果 頭文件 般的 gin

有可能會碰到兩個類之間的相互調用的問題,例如:定義了類A和類B,A中使用了B定義的類型,B中也使用了A定義的類型

class A {
    B b;
};

class B {
    A a;
};

  編譯器在聲明A的時候,由於B的聲明在A的下面所以出現編譯錯誤

那麽,在定義時如果要相互調用肯定會需要相互包含頭文件,如果僅僅只是在各自的頭文件中包含對方的頭文件,是通不過編譯的:

//a.h
#include"b.h"
class A {
public:
    B xianghuInA;
};

//b.h
#include"a.h"
class
B { public: A xianghuInB; };

怎麽辦?一般的做法是

1)class B采用前置聲明的方式聲明class A

2)在class B中只能聲明class A類型的指針,因為定義指針時不需要對那個類的定義可見

3)在class A的頭文件中包含class B 的頭文件

//a.h
#pragma once
#include"b.h"    //一定要有
class A {
public:
    B xianghuInA;
    int a = 1;
    void funA();
};
//b.h
#pragma once
#include
<iostream> class A; class B { public: int b = 5; A* xianghuInB = NULL; //一定要是指針 void funB(); ~B(); };
//a.cpp
#include"a.h"
#include<iostream>
using namespace std;

void  A::funA()
{
    cout << xianghuInA.b << endl;
}
//b.cpp
#include"
b.h" #include<iostream> #include <typeinfo> using namespace std; void B::funB() { cout << typeid(xianghuInB).name() << endl; } B::~B() { delete xianghuInB; }
//main.cpp
#include<iostream>
#include"a.h"
#include"b.h"
using namespace std;

int main()
{
    A qq;
    qq.funA();
    B hh;
    hh.funB();
    return 0;
}

運行結果:

技術分享圖片

c++兩個類相互調用