代碼如下
#include#include #include using namespace std; template class Base { public: Base(T name); virtual void toString(); protected: T id; }; template Base ::Base(T n) { printf("Base constructor!\n"); id = n; } template void Base ::toString() { cout<<"my id is "< class Derive:public Base { public: Derive(T id); }; template Derive ::Derive(T n):Base (n) { printf("Derive constructor!\n"); } int main(void) { Derive d(5); d.toString(); return 0; }
需要注意的是,派生類調用基類的構造函數是Base
如果沒有模板參數T,出現的錯誤是
../src/CTest.cpp: 在構造函數‘Derive::Derive(T)’中: ../src/CTest.cpp:41:24: 錯誤: 類‘Derive ’沒有名為‘Base’的字段 ../src/CTest.cpp: In instantiation of ‘Derive ::Derive(T) [with T = int]’: ../src/CTest.cpp:49:17: required from here ../src/CTest.cpp:41:30: 錯誤: 對‘Base ::Base()’的調用沒有匹配的函數 ../src/CTest.cpp:41:30: 附注: 備選是: ../src/CTest.cpp:21:1: 附注: Base ::Base(T) [with T = int] ../src/CTest.cpp:21:1: 附注: 備選需要 1 實參,但提供了 0 個 ../src/CTest.cpp:11:7: 附注: Base ::Base(const Base &) ../src/CTest.cpp:11:7: 附注: 備選需要 1 實參,但提供了 0 個 make: *** [src/CTest.o] 錯誤 1