首页 > 解决方案 > C++ 交叉包含——这正常吗?

问题描述

我学习 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

标签: c++classtemplates

解决方案


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

#include <iostream>

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

/// ... and some code here

推荐阅读