c++分文件編寫的編譯機制:
各個文件獨立編譯,如果在某.cpp文件中出現了函數調用,但是在此.cpp文件並沒有對應函數的實現。此時就會在函數調用出生成特定的符號,在之后的鏈接過程完成函數調用。
C++模板的編譯機制:
模板都會進行兩次編譯。當編譯器第一次遇到模板時進行一次普通的編譯,當調用函數模板時進行第二次編譯。第二次編譯將特定值帶入編譯如:
在分文件編寫類模板,不調用時。編譯是不會出現問題的。如下:
Car.h文件
1 #ifndef _CAR_H 2 #define _CAR_H 3 4 5 template<class T> 6 class Car{ 7 public: 8 Car(T c); 9 ~Car(); 10 T GetColor(); 11 private: 12 T Color;//顏色 13 }; 14 15 #endif
Car.cpp文件
#include"Car.h" #include <iostream> #include <string> using namespace std; template<class T> Car<T>::Car(T c) { this->Color = c; } template<class T> Car<T>::~Car() { cout << "~Car___析構函數" << endl; } template<class T> T Car<T>::GetColor() { return this->Color; }
mian.cpp文件
#include <iostream> #include <string> #include "Car.h" using namespace std; int main() { //沒有調用類模板 system("pause"); return 0; }
在沒用調用類模板的情況下編譯:(成功,這也很好的證明C++分文件編譯的機制)
如果將main.cpp改為如下情況在編譯:
#include <iostream> #include <string> #include "Car.h" using namespace std; int main() { Car<string>car("red"); car.GetColor(); system("pause"); return 0; }
在調用模板的情況編譯:(失敗,在main.cpp中調用了string GetColor()函數,在main.cpp中並沒有該函數而且在其他文件中也沒此函數)
解決方法:
1.將Car.cpp改為Car.hpp
2.將#include"Car.h"改為#include“Car.hpp”