【问题标题】:C++ cross-including -- is it normal?C++ 交叉包含——这正常吗?
【发布时间】: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 我知道,但是应该更改扩展名以便在编译时排除在 *.cpp glob 中

标签: c++ class templates


【解决方案1】:

感谢@Magix 的回答。现在我的a.cpp 更改为a.tpp,看起来像这样:

#include <iostream>

template <typename T>
void A<T>::func() {
    /// ... some code here
}

/// ... and some code here

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2012-04-10
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多