C++中兩個類交叉定義或遞歸定義的解決辦法

有兩個類這樣定義:
 

Subject.h 頭文件如下:
#ifndef SUBJECT_H
#define SUBJECT_H
#include <iostream>
#include "Observer.h"
 
class Subject
{
public:
       void Info(){ std::cout <<" Subject !/n"; }
protected:
private:
       Observer myObserver;
};
#endif
 
 
Subject.h 頭文件如下:
#ifndef OBSERVER_H
#define OBSERVER_H
#include <iostream>
#include "Subject.h"
 
class Observer
{
public:
       void PrintInfo(){std::cout<<" In Observer !"<<std::endl;}
protected:
private:
       Subject mySubject;
};
#endif
在主文件中引用這兩個類:
#include <iostream>
using namespace std;
#include "Subject.h"
#include "Observer.h"
 
int main()
{
       Observer myObser;
       myObser.PrintInfo();
 
       Subject myS;
       myS.Info();
       return 0;
}
 
這種情況屬於類的交叉定義。如複雜的觀察者模式中,Subject和Observer要相互註冊到對方。就會出現這種定義。
在這種情況下,編譯是通不過的。
編譯器的提示的錯誤如下:
syntax error : missing '';'' before identifier ''mySubject''
''Subject'' : missing storage-class or type specifiers
''mySubject'' : missing storage-class or type specifiers
 
錯誤表示找不到類的定義。因爲編譯器在爲具體的對象分配內存時,必要先知道其大小。而上述兩個類遞歸定義,編譯器如何分清對象的大小呢?
我們通過把類的數據成員修改成指針類型,告訴編譯器這個類的大小。並彼此加上類的前向聲明。如下:
Subject.h 頭文件如下:
#ifndef SUBJECT_H
#define SUBJECT_H
#include <iostream>
#include "Observer.h"
 
class Observer;
class Subject
{
public:
       void Info(){ std::cout <<" Subject !/n"; }
protected:
private:
       Observer *     myObserver;
};
#endif
 
Subject.h 頭文件如下:
#ifndef OBSERVER_H
#define OBSERVER_H
#include <iostream>
#include "Subject.h"
 
class Subject;
class Observer
{
public:
       void PrintInfo(){std::cout<<" In Observer !"<<std::endl;}
protected:
private:
       Subject*  mySubject;
};
 
事實上,只要打破類聲明的遞歸鏈,就能解決類定義找不到的問題。 

發佈了37 篇原創文章 · 獲贊 15 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章