模板编译模型
2019獨角獸企業重金招聘Python工程師標準>>>
學習C++ Primer第四版,P542的模板編譯模型的時候,按照上面的說法寫“包含模型”程序
utilities.h
#ifndef GUARD_UTILITIES_H #define GUARD_UTILITIES_Htemplate <class T> int compare(const T&, const T&); //模板函數的聲明#include "utilities.cpp" #endifutilities.cpp
#include "utilities.h"//implementation file utilities.cpp template <class T> int compare(const T &v1,const T &v2) {if(v1 < v2){return -1;}if(v2 < v1){return 1;}return 0; } #endifmain.cpp
#include "utilities.h" #include <iostream>using namespace std;int main() {const int a = 20;const int b = 20;int c;c = compare(a, b);cout << c << endl; } 結果出現錯誤:error C2995: “int compare(const T &,const T &)”: 函數模板已經定義
1> ? ? ? ?c:\users\lee\documents\visual studio 2008\projects\test\test\utilities.h(4) : 參見“compare”的聲明
后來在csdn上看了下,有以下三種解釋:
1.在.h文件中不包含.cpp;在main函數里#include?.cpp也可以
2.將utilities.cpp文件不包含在工程中,其他代碼比便,編譯通過可運行
非常好的解釋:
查了一些資料,終于弄明白了 原來C++ Primer是采用這樣的技術讓模板定義和實現分離 1. 在Queue.h文件的確寫有#include "Queue.cpp"(這是對的) ? ?????????????? ????????????????????????????????? ? ? ? ? ? ? ?2. 而建立的工程里面,并不把Queue.cpp包含進來(放在磁盤目錄下,但別加入工程),也就是Queue.cpp并不直接參與編譯鏈接,只有main()參加編譯,? ????????????????????????????????????????????????????????????????? ? ? ? ? ? ? ? ? ? ?3. 在main()所在的文件中,#include "Queue.h" 由于1和3的效果,使分離的模板定義和實現合并到了main()所在的文件中 而由于Queue.cpp本身不直接編譯(僅間接參與main()所在的文件的編譯),所以也不會出現重定義錯誤 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ???? ???? 你之所以在windows下用命令行中用nmake可以編譯成功,是因為他的makefile文件里面就是按上述要求寫的,即makefile指明只編譯main()所在的文件 3.將定義和聲明放在一個文件中,不要分開弄
參考地址:http://bbs.csdn.net/topics/320028181
轉載于:https://my.oschina.net/zjlaobusi/blog/138823
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: Android 4.0操作系统的20个使
- 下一篇: SVN常见错误