【发布时间】:2018-10-17 03:07:03
【问题描述】:
我学习 C++ 已经有一段时间了(没那么久),现在我遇到了一个问题:
#ifndef _FILE_A_H
#define _FILE_A_H
template <typename T>
class A {
void func();
/// ... some code here
};
#include "a.cpp"
#endif
我想将 A 类的实现放在文件 'a.cpp' 中。但要做到这一点,我需要包含'a.h'。在这种情况下交叉包含文件是否正常?
我在'a.cpp' 中有这样的东西(它正在编译但看起来很尴尬):
#ifndef _FILE_A_CPP
#define _FILE_A_CPP
#include "a.h"
template <typename T>
void A<T>::func() {
/// ... some code here
}
/// ... and some code here
#endif
【问题讨论】:
-
你不需要在头文件中包含
a.cpp。没有它它应该编译得很好,并且当你这样做时应该会导致双定义错误! -
与您的问题无关,但所有以下划线开头后跟大写字母(如
_FILE_A_H)的符号都保留。参见例如this question and answer了解详情。 -
@Magix 注意这是一个模板类。stackoverflow.com/questions/495021/…
-
将模板实现完全保存在 .h 文件中更为正常,这样您就不必为这个难题而苦恼了。
-
@BoPersson 我知道,但是应该更改扩展名以便在编译时排除在
*.cppglob 中