类模板基本运用

本文详细介绍了C++中类模板的使用方法,包括无类型参数的类模板、带有整型常量参数的类模板以及多参数类模板的具体实现。通过实例展示了如何定义和使用这些类模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//类模板
#include"aa.h"
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<fstream>
#include<sstream>
#include<iomanip>
#include<string>
using namespace std;
template <class t1>
class bb
{
public:
int i;
bb()
{
this->i=2;


}
};
template <class t1,class t2>
class aa:public bb<t1>
{
public :
bb<t2> add(bb<t2>,t2);


};
template <class t1,class t2>
bb<t2> aa<t1,t2>::add(bb<t2> i,t2 j)
{
return i;
}
int main()
{
aa<double,int> a1;
bb<int> b1;
b1=a1.add(b1,1);
cout<<b1.i<<endl;
return 0;
}


//类模板参数除了类型参数外,还可以是标准的数据类型


#include"aa.h"
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<fstream>
#include<sstream>
#include<iomanip>
#include<string>
using namespace std;
template <class t,int i>
class bb
{
public:

void test(t t1)
{int k=t1+i;
cout<<k<<endl;


}
};


int main()
{
bb<int,2> b;
b.test(2);
return 0;
}
//类模板参数也可以没有类型参数


#include"aa.h"
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<fstream>
#include<sstream>
#include<iomanip>
#include<string>
using namespace std;
template <int i>
class bb
{
public:

int k[i];
bb()
{


}
};


int main()
{
bb<2> b;


return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值