首页 > 代码库 > homework 15 2016 6 2 模板

homework 15 2016 6 2 模板

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;

template <typename T, int capacity>

class Array

{
  public:     
    Array(); 
    ~Array();
    bool empty();
    void push(T value);
    T pop();
    int size();
    T& operator[] (int index);

private:
    T* elements; 
    int num;
};


class ArrayException

{

  public: 
       ArrayException(const char *msg);
       const char *what() const;
  private:
       const char *message;
};

 

 

 

 

 

template <typename T, int capacity>
Array<T,capacity>::Array(){
 num = 0;
    elements = new T[capacity];

template <typename T, int capacity>                     
Array<T,capacity>::~Array(){
    delete [] elements;
}

template <typename T, int capacity>                  
bool Array<T,capacity>::empty(){
    if(num==0) return true;
    else return false;
}   

template <typename T, int capacity>
void Array<T,capacity>::push(T value){
    if(num >= capacity) throw ArrayException("Array Full Exception");
    else {
        elements[num] = value;
        num++;
    }
}

template <typename T, int capacity>
T Array<T,capacity>::pop(){
    if(num == 0) throw ArrayException("Array Empty Exception");
    else {
        T temp = elements[num-1];
        elements[num-1] = 0;
        num--;
        return temp;
    }
}


template <typename T, int capacity>
int Array<T,capacity>::size(){
 return num;
}

template <typename T, int capacity>
T& Array<T,capacity>::operator[] (int index){
    if(index < 0 || index >= num) throw ArrayException("Out of Range Exception");
    else return elements[index];
}

ArrayException::ArrayException(const char *msg){
 message=msg;
}

const char* ArrayException::what() const{
    return message;
 
}

 


void test()
{
Array<int,1> intArray;


try {
    intArray.push(1);
}

catch (ArrayException ex) {
     cout << ex.what() << endl;
}

try {

     cout << intArray[3] << endl;

}

catch (ArrayException ex) {

     cout << ex.what() << endl;

}

try {

     cout << intArray.pop() << endl;

}

catch (ArrayException ex) {

    cout << ex.what() << endl;
}

}
int main(){
 
 
    Array<int,15> a;
 for (int i = 0; i <15; i++) a.push(i);
 cout<<"a.size=="<<a.size()<<endl;
 cout<<"a[0]=="<<a[0]<<endl;
 cout<<"a[a.size()-1]=="<<a[a.size()-1]<<endl;
 cout<<"a[-1]=="<<a[-1]<<endl;
 cout<<"a[a.size()]=="<<a[a.size()]<<endl;

 cout << endl;
 
 return 0;
 
}

homework 15 2016 6 2 模板