【2017年整理】c++7模板和STL.ppt
文本预览下载声明
模板与标准模板库;代码重用的另一种方式:模板类
7.1 模板的基本知识
一个模板类至少具有一个类参数,类参数是个符号以表示将要被某个确定数据类型代替的类型。
class intArray
{
public:
int operator [ ] ( int );
const int operator[ ] ( int ) const;
intArray( int );
~intArray();
int get_size() const { return size; };private:
int* a;
int size;
intArray(); //*** for emphasis
int dummy_val; //arbitrary value
};
int intArray::operator [] ( int i )
{
if (i 0 || i = size)
{
cerr index i Out of bounds: ;
return dummy_val;
}
return a[i];
};const int intArray::operator[] ( int i ) const
{
if (i 0 || i = size)
{
cerr index i Out of bounds: ;
return dummy_val;
}
return a[i];
}
intArray::intArray( int s )
{
a = new int[ size = s ];
}
intArray::~intArray()
{
delete [] a;
};//#################################
//######### 模板类方式 #############
//#################################
template class T
class Array
{
public:
T operator [] ( int );
const T operator[] ( int ) const;
Array( int );
~Array();
int get_size() const { return size; }
private:
T* a;
int size;
Array(); //*** for emphasis
T dummy_val; //arbitrary value
};;template class T
T Array T ::operator [] ( int i )
{
if (i 0 || i = size)
{
cerr index i Out of bounds: ;
return dummy_val;
}
return a[i];
};template class T
const T Array T ::operator[] ( int i ) const
{
if (i 0 || i = size)
{
cerr index i Out of bounds: ;
return dummy_val;
}
return a[i];
};template class T
Array T ::Array( int s )
{
a = new T[ size = s ];
}
template class T
Array T ::~Array()
{
delete [] a;
}
;template class T
ostream operator ( ostream os, const Array T ar)
{
for ( int i = 0; i ar.get_size(); i++ )
os ar[ i ] endl;
return os;
};7.1.1 模板实???
#include iostream
using namespace std;
//declaration of template class Array
int main()
{
Array double a1(100); //array of 100 doubles
a1[ 6 ] = 3.14;
couta1[6]endl;
//...
};例子:
template class T
class Array
{
//...
};
Array a0(50);
Array T a1( 50 );
template class T
显示全部