代码如下
#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