嵌套类包含标头
Nested class include header
我有一个类看起来像这样:
// List.hpp
template<typename T>
class List {
...
private:
class Node;
};
我想把List<T>::Node
的完整定义放在一个单独的文件中:
// Node.hpp
template<typename T>
class List<T>::Node {
...
};
我的问题是,我应该在每个文件中包含什么,以及将#include
放在哪里?
最简单的方法(我认为)是在List.hpp
的末尾包含Node.hpp
,而不在Node.hpp
中包含任何内容。然而,这使得Node.hpp
本身并不是一个完整的文件(比如说,如果我在IDE或其他地方打开它,由于缺少List<T>
的定义,会有很多错误)。此外,我不确定是否可以将#include
放在文件的底部。
假设每个文件都有自己的包含保护#define
,我也可以在Node.hpp
的顶部包含List.hpp
(让IDE高兴),然后在List.hpp
的底部再次包含Node.hpp
,但我不知道这是否是个好主意。
编译List<T>::Node
的成员函数时,编译器始终需要模板类List
的可见性。其结果是,任何需要Node.hpp
的内容的可见性的编译单元都需要List.hpp
的内容(模板化成员的定义)的可见性。
最简单的选项是将Node.hpp
的内容放在List.hpp
的末尾,并且仅将#include "List.h"
放在需要任一模板的编译单元中。这完全消除了对Node.hpp
的需要。
如果您真的必须同时拥有这两个标头(这对我来说似乎是任意的,毫无意义,因为List<T>::Node
是List<T>
的一个组件),那么一个选项是帮助包含保护。
// List.hpp
#ifndef LIST_HPP_INCLUDED // some unique macro
#define LIST_HPP_INCLUDED
// definition of templated class List
#include "Node.hpp" // this must be after the definition of List<T>
#endif
和Node.hpp
// Node.hpp
#ifndef NODE_HPP_INCLUDED // some unique macro
#define NODE_HPP_INCLUDED
#include "List.hpp" // this must precede the definitions for List<T>::Node
// definition of templated class List<T>::Node
#endif
这允许任何编译单元将任一标头设为#include
d,并且include保护停止无限递归include。
大多数现代IDE都能应付这种情况。如果你有一个没有,那么简单地转换到一个单独的头文件。
- 嵌套包含在C++中
- 派生自嵌套在类模板中的类模板,所有这些都包含在类模板中
- 无法从多态嵌套类访问包含类的成员
- 矢量下标超出范围,带有嵌套的 for 循环
- 如何打破定义嵌套模板类的标头的圆形依赖关系
- 包含指针成员的嵌套结构
- 为什么我在编译中经常出现错误:包含嵌套太深的 C++
- C++ 我是否需要为嵌套类定义标头保护
- 包含整数平均值的嵌套循环
- 尽管包含头文件,但仍找不到嵌套命名空间
- 协议缓冲区-读取所有消息中通用的标头(嵌套消息)
- MSVC 2003 看不到嵌套包含文件中的任何定义
- 嵌套 while 循环,包含文件 c++ 问题
- 如何在给定包含类的实例的情况下实例化嵌套类
- 嵌套类包含标头
- 为什么OpenCV Mat对象在嵌套for循环中指定了预期值后却不包含这些值
- 外部类的嵌套类定义,而外部类包含内部类的实例
- 允许嵌套结构具有包含类的实例
- 封送包含布尔值的复杂嵌套结构
- 如何将我的实现包含在一些头文件(嵌套类)的cpp文件中