zoukankan      html  css  js  c++  java
  • C++模板template的基本使用

    一:模板定义:模板就是实现代码重用机制的一种工具,它可以实现类型参数化,即把类型定义为参数, 从而实现了真正的代码可重用性。模版可以分为两类,一个是函数模版,另外一个是类模版。

    二:模板的;两种声明方式:1.template<class T>     2.template<typename T>

    三:两种模板的举栗

    1.函数模板

     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <cstdio>
     5 using namespace std;
     6 
     7 template<class T>
     8 void Swap(T& a,T& b){
     9     T temp;
    10     temp = a;
    11     a = b;
    12     b = temp;
    13 }
    14 int main(){
    15     int a = 1,b = 2;
    16     printf("a=%d,b=%d
    ",a,b);
    17     Swap<int>(a,b);
    18     printf("a=%d,b=%d
    ",a,b);
    19     system("pause");
    20 } 

    2.类模板

     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <cstdio>
     5 using namespace std;
     6 template<class T>
     7 class Stack{
     8 private :
     9     T *m_ptr;
    10     int m_size;
    11     int m_n;
    12 public:
    13     Stack();
    14     ~Stack();
    15     void push(T t);
    16     T pop();
    17     bool isEmpty();
    18 };
    19 
    20 template<class T> Stack<T>::Stack(){
    21     m_size = 100;
    22     m_ptr = new T[m_size];
    23     m_n = 0;
    24 }
    25 template<class T> Stack<T>::~Stack(){
    26     delete [] m_ptr;
    27 }
    28 template<class T> void Stack<T>::push(T t){
    29     m_ptr[m_n++] = t;
    30 }
    31 template<class T> T Stack<T>::pop(){
    32     return m_ptr[--m_n];
    33 }
    34 template<class T> bool Stack<T>::isEmpty(){
    35     return m_n == 0 ? true : false;
    36 }
    37 int main(){
    38     Stack<int> stack;
    39     stack.push(1);
    40     stack.push(2);
    41     stack.push(3);
    42     while(!stack.isEmpty()){
    43         printf("%d
    ",stack.pop());
    44     }
    45     system("pause");
    46 }
  • 相关阅读:
    SVG
    颜色的小纠结
    Tomcat 安装与配置
    编译java代码出现 错误: 需要class, interface或enum 提示
    Java 开发环境配置
    关于shortcut icon和icon
    转载文章CSS3的calc()使用
    小tip:CSS vw让overflow:auto页面滚动条出现时不跳动——张鑫旭
    CSS计数器(序列数字字符自动递增)详解———张鑫旭
    一起来看看JavaScript中==和===有何不同
  • 原文地址:https://www.cnblogs.com/yjb333/p/9339038.html
Copyright © 2011-2022 走看看