类模版小实例

本文介绍了C++中的模板概念,包括模板声明、模板类的定义(如compare类),以及如何使用默认模板参数。通过实例化Stack模板创建堆栈类,展示了模板在实际编程中的应用。
摘要由CSDN通过智能技术生成

目录

声明

定义一个模版类

默认模板实参


模板是一个非常强大的C++功能,STL的各种组件也是基于模板的。所以,无论是写程序了,还是读程序,都有必要了解一下C++的模板。

声明

template <typename T>  int compare (T t1, T t2);
//声明了T之后就可以把T当成一种类型去使用

 今天的重点是模版类

定义一个模版类

template <typename T>
class compare
{
private:
    T _val;
public:
    explicit compare(T & val) : _val(val) { }
    explicit compare(T && val) : _val(val) { }
    bool operator==(T & t)
    {
        return _val == t;
    }
};
int main() {
    int a = 10;
    compare<int> comp(a); // 实例化 compare 类,并将 a 的值传入构造函数

    int b = 15;
    if (comp == b) {
        std::cout << "a 和 b 相等" << std::endl;
    } else {
        std::cout << "a 和 b 不相等" << std::endl;
    }

    return 0;
}

关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生,声明为explicit的构造函数不能在隐式转换中使用。这个我们以后再说。

由于编译器并不会直接编译模板本身,所以模板的定义通常放在头文件中。

默认模板实参
template <typename T = int> class A;
A<> a; // T is int

好了,进入今天的整体:案例!

这是一个关于堆栈的小案例

头文件:stacktp.h

// stacktp.h -- a stack template
#ifndef STACKTP_H_
#define STACKTP_H_

template <class Type>
class Stack
{
private:
    enum
    {
        MAX = 10
    };               // constant specific to class
    Type items[MAX]; // holds stack items          用于存储堆栈项目的数组
    int top;         // index for top stack item   用于表示堆栈顶部的索引
public:
    Stack();
    bool isempty();              // 判断堆栈是否的为空成员函数
    bool isFull();               // 判断堆栈是否的已满成员函数
    bool push(const Type &item); // add item to stack    将项目推入堆栈的成员函数
    bool pop(Type &item);        // pop top into item    从堆栈中弹出项目的成员函数
};

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(const 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;
}

#endif // STACKTP_H_

#ifndef和#endif是为了防止头文件被多次编译的关键字,bool是布尔类型,用于一些判断的函数有奇效

stacktem.cpp

// stacktem.cpp -- testing the template stack class
#include <iostream>
#include <string>
#include <cctype>
#include "stacktp.h"
using std::cin;
using std::cout;

int main()
{
    Stack<std::string> st; // create an empty stack
    char ch;
    std::string po;
    cout << "Please enter A to add a purchase order.\n"
        << "P to process a PO, or Q to quit.\n";
    while (cin >> ch && std::toupper(ch) != 'Q')
    {
        while (cin.get() != '\n')
            continue;
        if (!std::isalpha(ch))
        {
            cout << '\a';
            continue;
        }
        switch (ch)
        {
        case 'A':
        case 'a':
            cout << "Enter a PO number to add: ";
            cin >> po;
            if (st.isFull())
                cout << "stack already full\n";
            else
                st.push(po);
            break;
        case 'P':
        case 'p':
            if (st.isempty())
                cout << "stack already empty\n";
            else
            {
                st.pop(po);
                cout << "PO #" << po << " popped\n";
                break;
            }
        }
        cout << "Please enter A to add a purchase order.\n"
            << "P to process a PO, or Q to quit.\n";
    }
    cout << "Bye\n";
    return 0;
}

运行示例:

PS E:\VScode code>  & 'c:\Users\hp\.vscode\extensions\ms-vscode.cpptools-1.19.8-win32-x64\debugAdapters\bin\WindowsDebugLauncher.exe' '--stdin=Microsoft-MIEngine-In-gjgxgr5v.mce' '--stdout=Microsoft-MIEngine-Out-052o12v3.35b' '--stderr=Microsoft-MIEngine-Error-jrpqxszp.tis' '--pid=Microsoft-MIEngine-Pid-tsb1p3mq.y0c' '--dbgExe=C:\Program Files (x86)\mingw64\bin\gdb.exe' '--interpreter=mi' 
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
A
Enter a PO number to add: ysy
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
A
Enter a PO number to add: hjy
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
A
Enter a PO number to add: gzm
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
A
Enter a PO number to add: cn
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
P
PO #cn popped
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
P
PO #gzm popped
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
P
PO #hjy popped
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
P
PO #ysy popped
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
P
stack already empty
Please enter A to add a purchase order.
P to process a PO, or Q to quit.
Q
Bye

仅为拙见,还有不足,望大佬指正

  • 15
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值