您的位置:首页 > 编程语言 > C语言/C++

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

2014-04-30 19:06 239 查看
代码如下

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息