一、两个类相互包含的示范
A.h
/*A.h*/
#ifndef __A_H__
#define __A_H__
#include "B.h"
class A
{
B* b;
};
#endif
B.h
/*B.h*/
#ifndef __B_H__
#define __B_H__
#include "A.h"
class B
{
private:
A* a;
};
#endifA.cpp
#include "A.h"
B.CPP
#include "B.h"
编译命令:
g++ main.cpp A.cpp B.cpp -o main
报错:
In file included from A.h:5:0,
from main.cpp:1:
B.h:10:5: error: ‘A’ does not name a type
A* a;
^
adminer@ubuntu:~/work_space/zhangkesong/CrossLineApp/lib$ g++ main.cpp A.cpp B.cpp -o main
In file included from A.h:5:0,
from main.cpp:1:
B.h:10:5: error: ‘A’ does not name a type
A* a;
^
In file included from A.h:5:0,
from A.c

本文探讨了在编程中遇到的两个类相互包含导致的编译错误,提出了解决思路,包括使用void*指针以及将其中一个类的定义移到cpp文件中以避免头文件循环引用的问题,并提供了具体的实现示例。

1122

被折叠的 条评论
为什么被折叠?



