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

关于c++模板的一些问题

2010-05-20 22:11 281 查看
/***************************** 关于c++中模板类的一些说明***********************************

c++中模板是怎么定义及使用,特别是类模板问题.下面例子定义了一个模板类,再声明一个对象,进行测试.
在我看来,其实模板类同普通的类相似,不同之处在于,在类函数定义时都需有template < class T, int i >
(注意此处没有分号),接着写TestClass< T,i >相当于我们的类是 TestClass< T,i > ,相比我们平常的类,
可以理解为TestClass< T,i >是平常类加了参数,其他照写.类的定义与实现须在同一个文件下,如例子全
写在fig.h中,如果在fig.h定义类,再用fig.cpp来实现类的话,则会报错.

/*********************************************************/

#include <iostream.h>
#include "fig.h"
int main()
{
TestClass< int,10 > c(10);
c.print();
}

// fig.h
// define class testclass
#ifndef FIG_H
#define FIG_H
#include <iostream.h>

template < class T, int i >
class TestClass {
public:
TestClass( T num ); // 构造函数
T buffer[i]; // 一个数组
void print() const; // 将结果打印
};

template < class T, int i >
TestClass< T,i >::TestClass( T num )
{
for( int j=0;j<i;j++)
buffer[j] = num;
}
template < class T, int i >
void TestClass<T,i>::print() const
{
for( int j=0;j<i;j++)
cout<<buffer[j]<<'\t';
}

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: