class Stash int quantity int next int storage

  • Slides: 23
Download presentation

类模板 和函数一样,类同样具有类 class Stash { 型依赖性。在定义类的时侯, int quantity; int next; 类中的数据成员、成员函数 int* storage; 的返回值以及参数都必须有

类模板 和函数一样,类同样具有类 class Stash { 型依赖性。在定义类的时侯, int quantity; int next; 类中的数据成员、成员函数 int* storage; 的返回值以及参数都必须有 void inflate(int 确定的类型,有时候这也会 public: 妨碍类代码的可重用性。 Stash(); Stash(int init. Quantity); ~Stash(); int add(int& element); int& fetch(int index) const; int& operator[](int index) const; int count() const; 问题——定义动态数组 元素个数应可动态变化 元素类型应没有限制 例子: Stash. h Stash. cpp Stash. Test. cpp increase); };

类模板 同函数模板一样,一个类模 Template<class T> 板实际上对应了一组类。 class Stash { 当定义一个模板类的对象时, int quantity; int next; 程序员需要提供模板实参,

类模板 同函数模板一样,一个类模 Template<class T> 板实际上对应了一组类。 class Stash { 当定义一个模板类的对象时, int quantity; int next; 程序员需要提供模板实参, T* storage; C++编译器根据程序员提供 void inflate(int increase); 的模板实参生成一个个具体 public: Stash(); 的适合不同类型的类定义, Stash(int init. Quantity); 形式如下: ~Stash(); int add(T& element); T& fetch(int index) const; T& operator[](int index) const; int count() const; 类名<模板实参> 对象名. . . Stash<int> int. Stash; Stash<float> float. Stash; };

类模板 C++编译器根据模板实参生成类的过程被称为类模板例化。 T=int Stash<int> T=student Stash<student> class Stash { int quantity; classint Stash {

类模板 C++编译器根据模板实参生成类的过程被称为类模板例化。 T=int Stash<int> T=student Stash<student> class Stash { int quantity; classint Stash { next; intint* quantity; storage; intvoid next; inflate(int increase); student* public: storage; void inflate(int increase); Stash(); public: Stash(int init. Quantity); Stash(); ~Stash(); Stash(int init. Quantity); int add(int& element); ~Stash(); int& fetch(int index) const; intint& add(student& element); operator[](int index) const; student& fetch(int index) const; int count() const; student& operator[](int index) const; }; int count() const; };

类模板 template <typename T, int increment> Stash<T, increment>: : Stash() : quantity(0), next(0), storage(0)

类模板 template <typename T, int increment> Stash<T, increment>: : Stash() : quantity(0), next(0), storage(0) { } template <typename T, int increment> Stash<T, increment>: : ~Stash() { if(storage != 0) delete []storage; } template <typename T, int increment> int Stash<T, increment>: : add(T& element) { if(next >= quantity) inflate(increment); storage[next] = element; next++; return(next - 1); }