C++中两个类交叉定义或递归定义的解决办法

来源:互联网 发布:mac pro上没有USB 编辑:程序博客网 时间:2024/05/29 13:29

有两个类这样定义:
 

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;
};
 
事实上,只要打破类声明的递归链,就能解决类定义找不到的问题。 

原创粉丝点击