博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++中两个类交叉定义或递归定义的解决办法
阅读量:2178 次
发布时间:2019-05-01

本文共 1508 字,大约阅读时间需要 5 分钟。

有两个类这样定义:

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

转载地址:http://snckb.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】228-Summary Ranges
查看>>
【LEETCODE】27-Remove Element
查看>>
【LEETCODE】66-Plus One
查看>>
【LEETCODE】26-Remove Duplicates from Sorted Array
查看>>
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
【LEETCODE】88-Merge Sorted Array
查看>>
【LEETCODE】19-Remove Nth Node From End of List
查看>>
【LEETCODE】125-Valid Palindrome
查看>>
【LEETCODE】28-Implement strStr()
查看>>
【LEETCODE】6-ZigZag Conversion
查看>>
【LEETCODE】8-String to Integer (atoi)
查看>>
【LEETCODE】14-Longest Common Prefix
查看>>
【LEETCODE】38-Count and Say
查看>>
【LEETCODE】278-First Bad Version
查看>>
【LEETCODE】303-Range Sum Query - Immutable
查看>>
【LEETCODE】21-Merge Two Sorted Lists
查看>>
【LEETCODE】231-Power of Two
查看>>
【LEETCODE】172-Factorial Trailing Zeroes
查看>>
【LEETCODE】112-Path Sum
查看>>