C++基础知识(五)类进阶:模板类

本文探讨了在C++中如何使用模板类来提高代码重用性,特别是在设计容器类时的优势。通过实例展示了如何将一个仅适用于unsigned long类型的Stack类改造成模板类,以适应不同数据类型的存储需求。
摘要由CSDN通过智能技术生成

在某些场景下,继承和包含并不总是能满足重用代码的需要。比如,容器类。容器类设计用来存储其他对象或数据类型。
比如如下的Stack类:

Stack.h

#ifndef STACK_H_
#define STACK_H_
#include <iostream>
using namespace std;
typedef unsigned long Type;
class Stack{
private:
    enum {MAX = 10};
    Type items[MAX];
    int top;
public:
    Stack();
    bool isEmpty() const;
    bool isFull() const;
    bool push(const Type & item);
    bool pop(Type & item);
};

#endif /* STACK_H_ */

Stack.cpp

#include "Stack.h"
Stack::Stack(){
    top = 0;
}

bool Stack::isEmpty() const{
    return top == 0;
}

bool Stack::isFull() const{
    return top == MAX;
}

bool Stack:: push(const Type & item){
    if (top < MAX){
        items[top++] = item;
        return true;
    } else {
        return false;
    }
}

bool Stack::pop(Type & item){
    if (top > 0){
        item = items[--top];
        return true;
    } else {
        return false;
    }
}

上面的Stack类中只能存放unsigned long 类型,当需要存放其他类型时如果要重新写一个类,那未免太麻烦了。这种场景下,模板类就很实用了。
下面开始改造Stack类,使其成为一个模板类。使用模板定义替换Stack声明,使用模板成员函数替换Stack的成员函数。和模板函数一样,模板类采用如下开头:

template <typename Type>

在类声明和函数前添加模板声明:
Stack.h

#ifndef STACK_H_
#define STACK_H_
//typedef unsigned long Type;
template <class  Type>
class Stack{
private:
    enum {MAX = 10};
    Type items[MAX];
    int top;
public:
    Stack();
    bool isEmpty() ;
    bool isFull() ;
    bool push( Type  item);
    bool  pop(Type & item);
};

#endif /* STACK_H_ */

Stack.cpp

#include "Stack.h"
#include <iostream>
using namespace std;
template <class  Type>
Stack<Type>::Stack(){
    top = 0;
}

template <class  Type>
bool Stack<Type>::isEmpty() {
    return top == 0;
}

template <class  Type>
bool Stack<Type>::isFull() {
    return top == MAX;
}

template <class  Type>
bool Stack<Type>:: push( Type  item){
    if (top < MAX){
        items[top++] = item;
        return true;
    } else {
        return false;
    }
}

template <class  Type>
bool  Stack<Type>::pop(Type & item){
    if (top > 0){
         item = items[--top];
        return true;
    } else {
        return false;
    }
}

int main(){
    Stack<int> stack;
    int num = 5;
    stack.push(num);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值