c++调用基类的构造函数(模板类)

来源:互联网 发布:淘宝跑包 编辑:程序博客网 时间:2024/06/05 15:27


代码如下


#include <stdlib.h>#include <stdio.h>#include <iostream>using namespace std;template<class T>class Base{public:Base(T name);virtual void toString();protected:T id;};template<class T>Base<T>::Base(T n){printf("Base constructor!\n");id = n;}template<class T>void Base<T>::toString(){cout<<"my id is "<<id<<endl;}template<class T>class Derive:public Base<T>{public:Derive(T id);};template<class T>Derive<T>::Derive(T n):Base<T>(n){printf("Derive constructor!\n");}int main(void){Derive<int> d(5);d.toString();return 0;}



需要注意的是,派生类调用基类的构造函数是Base<T>(n)这样子的,要加上模板参数,不然会编译错误。

如果没有模板参数T,出现的错误是

../src/CTest.cpp: 在构造函数‘Derive<T>::Derive(T)’中:../src/CTest.cpp:41:24: 错误: 类‘Derive<T>’没有名为‘Base’的字段../src/CTest.cpp: In instantiation of ‘Derive<T>::Derive(T) [with T = int]’:../src/CTest.cpp:49:17:   required from here../src/CTest.cpp:41:30: 错误: 对‘Base<int>::Base()’的调用没有匹配的函数../src/CTest.cpp:41:30: 附注: 备选是:../src/CTest.cpp:21:1: 附注: Base<T>::Base(T) [with T = int]../src/CTest.cpp:21:1: 附注:   备选需要 1 实参,但提供了 0 个../src/CTest.cpp:11:7: 附注: Base<int>::Base(const Base<int>&)../src/CTest.cpp:11:7: 附注:   备选需要 1 实参,但提供了 0 个make: *** [src/CTest.o] 错误 1






0 0
原创粉丝点击