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 }
  • 相关阅读:
    scanf与scanf_s的区别
    C语言输出时的各种%
    Windows下配置OpenGL环境
    C#高级进阶--重写函数
    Linux下安装国际版QQ (转)
    Linux Vim不明原因卡死解决办法
    iCamera App Kit 使用说明
    usb2.0高速视频采集之68013A寄存器配置说明
    iSensor APP 之 摄像头调试 OV5642 续集2
    iSensor APP 之 摄像头调试 OV9655 测试之二
  • 原文地址:https://www.cnblogs.com/yjb333/p/9339038.html
Copyright © 2011-2022 走看看