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


代码如下


#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






  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值