C++[第十九章]--类模板

文章详细介绍了C++中的类模板,包括如何声明、定义和使用。类模板提供了一种泛型编程的方式,允许在不同数据类型上重用代码。通过实例化,可以创建针对特定类型的类对象。此外,还提到了类模板的特化,即对特定类型定制功能。
摘要由CSDN通过智能技术生成

类模板

1、格式

1. 声明
template<typeclass T>
class AAA 
/* 使用T表示某种类型,比如: */
private:
	T obj;
public:
	void test_func(T& t);
	.....
;

2. 定义
template<typeclass T>
void AAA<T>::test_func(T& t)  .... 

2、使用

方法一:用到时再实例化:

AAA<int> a;
AAA<double> b;

方法二:事先实例化:

template AAA<int>;
再使用:
AAA<int> a;

3、定做(类似重载)

//1. 声明
template<>
class AAA<int> 
......
public:
	void test(void);
;

//2. 定义
void AAA<int>::test(void) ...

例子:

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;


template<typename T>
class AAA {
private:
	T t;
public:
	void test_func(const T &t);
	void print(void);
};

template<typename T> void AAA<T>::test_func(const T &t)
{
	this->t = t;
}


template<typename T>
void AAA<T>::print(void)
{
	cout<<t<<endl;
}


/*定做*/
// template<>
// class AAA<int> {
// public:
// 	void test_func_int(const int & t)
// 	{
// 		cout<<t<<endl;
// 	}
// 	void print_int(void);
// };

// void AAA<int>::print_int(void)
// {
// 	cout<<"for test"<<endl;
// }

int main(int argc, char **argv)
{
	AAA<int> a;

	a.test_func(1.23);
	a.print();
	//a.test_func_int(1);
	//a.print_int();

	AAA<double> b;

	b.test_func(1.23);
	b.print();

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起风就扬帆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值