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;
};
事实上,只要打破类声明的递归链,就能解决类定义找不到的问题。
- C++中两个类交叉定义或递归定义的解决办法
- C++中两个类交叉定义或递归定义的解决办法
- (转)C++中两个类交叉定义或递归定义的解决办法
- C++中两个类交叉定义的处理方法
- C/C++由于头文件重复引入引起的成员或类重复定义的解决办法
- JS中类或对象的定义
- C++在两个类的头文件中相互定义变量,出现超前引用的情况的解决办法
- Objective-c中类的定义
- object-c中类的定义
- object-c中类的定义
- C中FILE的定义
- javaScript中定义类或对象的五种方式
- javaScript中定义类或对象的五种方式
- javaScript中定义类或对象的五种方式
- 递归的定义
- 定义递归的级数
- 递归的定义
- c++ 中类重复定义的分析与解决办法
- 保持屏幕常亮
- 记录一个在SharePoint的代码中提升运行权限的方法
- 调用setting的校准屏幕功能
- 自定义Ext组件的一些提示和技巧
- DOM解析XML文档
- C++中两个类交叉定义或递归定义的解决办法
- SIMPLEIME开发
- 管理Exchange Server 2007传输拓扑
- Exchange Server 2007非邮箱服务器失败规划和恢复
- Jquery 扩展
- Linux设备模型
- Exchange Server 2007邮箱存储服务器的集群和高可用性技术(上)
- Exchange Server 2007邮箱存储服务器的集群和高可用性技术(下)
- Exchange Server 2007邮箱服务器失败规划和恢复