1.模板函数
建立一个通用函数,其函数类型和形参不具体指定,用一个虚拟类型来代替。
格式:template<typename T>
int swap(T x, T y)
T可以变成任意类型,在赋实参时自动转变。
2.类模板
类中含有虚拟类型。
格式:template <typename T>
class A
{
T m_a;
int m_b;
}
下面写一个程序,模板类中构造函数,重载【】和 = 操作,通过多文件编译。
1)首先创建.h文件 Array.h
#ifndef _ARRAY_H_ #define _ARRAY_H_ #include <iostream> using namespace std; template <typename T> class Array { public: T *m_a; int m_length; public: Array(T *a,int n) { m_length = n; m_a = a; cout << "Array Constructor!" << endl; } int &operator ==(T *a) { if(m_a == a) return 1; else return 0; } T &operator [](int index) { return this -> m_a[index]; } friend ostream &operator <<(ostream &out,const Array &c) { for(int i = 0;i < c.m_length;i++) { out << c.m_a[i] << " "; } return out; } Array &operator =(Array &a) { cout << "dasdq\n" << endl; if(*this == a) { return *this; } this -> m_length = a.m_length; this -> m_a = a.m_a; return *this; } ~Array() { cout << "Array DesConsturctor!" << endl; } }; #endif
2)创建.cpp文件,main.cpp
#include <iostream> #include "Array.h" using namespace std; int main(int argc, char **argv) { int a[] = {5,4,8,7,9,3,6}; int n = sizeof(a)/sizeof(int); Array <int> A(a,n); if(A.m_a == a) { cout << "TRUE" << endl; } else { cout << "FALSE" << endl; } cout << A.m_a[5] << endl; Array <int>B = A; cout << A << endl; cout << B << endl; return 0; }