C++ 模板与泛型编程

泛型编程旨在编写独立于数据类型的代码” 《c++ primer plus》(6th ed)

实现一种方法,可以用于各种类型的数据。

#include<iostream>

using namespace std;

template <class Nott>
class Stack{
  private:
    Nott arr[20];
    int num;
  public:
    Stack();
    void push(const Nott& ele);
    void print();
};


template <class Nott>
Stack<Nott>::Stack(){
  num = 0;
}

template <class Nott>
void Stack<Nott>::push(const Nott& ele){
  arr[num] = ele;
  num ++; 
}

template <class Nott>
void Stack<Nott>::print(){
  for(int i = 0;i < num;i ++) 
    cout << arr[i] << " ";
  cout << endl;
}

int main(){
  Stack<char> nott;
  nott.push('N');
  nott.push('O');
  nott.push('T');
  nott.push('T');
  nott.print();
  Stack<int> nottt;
  nottt.push(6);
  nottt.push(6);
  nottt.push(6);
  nottt.push(6);
  nottt.print();
  return 0;
}

输出结果:

I C B C
6 6 6 6

Leave a Reply

Your email address will not be published. Required fields are marked *