C++ 连接两个 .cpp 文件

标签 c++

我在 C++ 中连接两个 .cpp 文件时遇到问题。这是我的文件

标题.h

//Header.h
template <class T> class asd{
asd();
check();
print();
}

文件1.cpp

//file1.cpp
//defines all methods in class asd
#include "Header.h"
template<class T> asd<T>:: asd(T a, T b){//codes}
template<class T> T asd<T>:: check(T a){//codes}
template<class T> void asd<T>::print(){//codes}

文件2.cpp

//file2.cpp
//main method
#include "Header.h"
int main(){//codes}

我不明白的是,当我将 main() 放在 file1.cpp 中时,代码运行良好,但当我将它们分成两个文件时,它不会编译。有人可以指点一下吗?

编辑: 对于有同样问题的人,可以在这里找到解决方案: http://www.cplusplus.com/forum/articles/14272/

最佳答案

类模板的成员函数应该出现在头文件中。只需将函数定义从 file1.cpp 移走即可至Header.h .

想象你是编译器。编译时main ,如果您尝试实例化 asd无论如何,编译器需要能够查看函数定义以生成适当的代码。例如,如果在 main你做asd<int> my_asd; ,编译器需要实例化asdT替换为 int 。如果看不到函数定义,它就无法对函数执行此操作。

关于C++ 连接两个 .cpp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15603059/

相关文章:

c++ - Linux套接字程序只是卡住而没有错误

c++ - 以编程方式检索 QSS 样式表属性的值

c++ - 创建线程安全单例时的临界区初始化(C++)

c++ - 将二维数组传递给 double function_name 时出错

c++ - 通常的算术转换如何工作?

c++ - 从 accumulator_set 中删除或修改 accumulators::tag

java - 我们需要Java++吗?

c++ - 如何用多态实现数据局部性?

使用较小内存量时出现 C++ std::bad_alloc 错误?

c++ - 对象被其他对象引用时const限定符的微妙问题