类模板的作用基本上和函数模板差不多,主要是为了省事和减少不必要的重复的代码,比如定义一个类 其私有数据是整型但是呢,你可能会需要用到double类型数据,但是类的成员函数基本上作用一样,这时候你就需要用到类模板,首先 定义类模板
template<Class T> //定义类模板
一.
后面紧跟着是定义的类
template<Class T>
class A {
private:
T a;
public:
A(const ai):a(ai) {}
A(const A & ai):(a = ai.a) {}
void printfOn() const;
};
后面是实现类的成员方法
每一个方法前面都必须要有一行模板定义
template<Class T>
void A<T>::printfOn() const {
std::cout << a << std::endl;
}
A<T> 表示类模板定义
重点: 不能将类模板成员函数放在独立的实现文件中 必须与类一起
当类成员函数指定返回类型或使用作用域解析运算符时,必须使用完整的A<T>
例如:
template<Class T>
class A {
private:
T a;
public:
A(const ai):a(ai) {}
A(const A & ai):(a = ai.a) {}
void printfOn() const;
A & operator=(const A & a); //有返回类型和运算符时
};
// 当类成员函数指定返回类型或使用作用域解析运算符时,必须使用完整的A<T>
template<Class T>
A<T> & A<T>::operator=(const A<T> & a) {
a = a.a;
return *this;
}
使用 指针特别注意 例如指针栈 它压入栈中的只是一个指向字符串的地址 并且构造函数需要动态创建内存大小,在析构函数中释放内存.
二.
另一种定义方式
array<array<int,5>,10> //使模板递归,相当于array[10][5] 二维数组
template<Class T,int n>
template<Class T=int> //表示T的类型为默认值 int类型
template <class T,int n>
class ArrayTp {
private:
T ar[n];
public:
ArrayTp() {};
explicit ArrayTp(const T & v);
virtual T & operator[](int i);
virtual T operator[](int i) const;
};
template <class T, int n>
ArrayTp<T, n>::ArrayTp(const T & v) {
for (int i = 0; i < n; i++) {
ar[i] = v;
}
}
template <class T, int n>
T & ArrayTp<T, n>::operator[](int i) {
if (i < 0 || i >= n) {
std::cerr << "Error in array limits: " << i <<
" is out range\n";
std::exit(EXIT_FAILURE);
}
return ar[i];
}
template <class T, int n>
T ArrayTp<T, n>::operator[](int i) const {
if (i < 0 || i >= n) {
std::cerr << "Error in array limits: " << i <<
" is out range\n";
std::exit(EXIT_FAILURE);
}
return ar[i];
}
int main() {
using namespace std;
ArrayTp<int, 10> sums;
ArrayTp<double, 10> aves;
ArrayTp<ArrayTp<int, 5>, 10>twodee;
int i, j;
for (i = 0; i < 10; i++) {
sums[i] = 0;
for (j = 0; j < 5; j++) {
twodee[i][j] = (i + 1) * (j + 1);
sums[i] += twodee[i][j];
}
aves[i] = (double)sums[i] / 10;
}
for (i = 0; i < 10; i++) {
for (j = 0; j < 5; j++) {
cout.width(2);
cout << twodee[i][j] << ' ';
}
cout << ": sum = ";
cout.width(3);
cout << sums[i] << ", average = " << aves[i] << endl;
}
cout << "Done.\n";
system("pause");
return 0;
}
template<int,2>a1;
template<int>a1(2); 调用构造函数(这是最常见的方法)