NEED HELP ASAP!!!!!!! I ALREADY DID THE PROGRAM IN MAIN I JUST NEED HELP TO SEPERATE IN .CPP, .H AND MAIN
-
THE QUESTION IS AS FOLLOWS:
Create a template class called Array that implements an array and works with any type (int, double, etc.). The constructor should take a size for the array and use new to allocate memory (don't forget to delete in the destructor). Overload operator[] to access the elements of the array. If an attempt is made to access an element outside the array bounds (either above OR below), throw an exception. In the main program, first create an Array<int> object, add a few values, and demonstrate that operator[] throws an exception if an attempt is made to access an out-of-bounds elements. Catch the exception and print an appropriate message. Then do the same thing with an Arraystd::string.
Hint: you will need both of these overloads:
T& operator[](int i)
const T& operator[](int i) const
I DID THE PROGRAM IN MAIN AS FOLLOWS AND IT DOES WELL IN THE MAIN BUT ITS GIVING ME HARD TIME DIVIDING IT INTO DIFFERENT FILES. #include "stdafx.h" #include <iostream> using namespace std; #include <exception> #include "Array.h" template <typename T> class Array { int size; T*array; public: Array(int s) { size=s; array=new T [size]; } ~Array() { delete [] array; } const T &operator[](int i) const { if(i < 0) throw exception("Index out of bounds LOWER"); else if(i>=size) throw exception("Index out of Bounds OVER"); else return array[i]; } }; int _tmain(int argc, _TCHAR* argv[]) { Array <int> num(12); try { int i=num[-1]; } catch (std :: exception & ex) { cout<<ex.what()<< endl; } Array <string> num1(12); try { string j=num1[14]; } catch (std :: exception & ex) { cout<<ex.what()<< endl; } cin.get(); cin.get(); return 0; } THEN I DIVIDED THE PROGRAM INTO DIFFERENT FILES AS FOLLOWS: IN ARRAY.H
#pragma once
template <typename T>
class Array
{
public:
Array(int s);
~Array();
const T &operator[](int i)const;
private:
int size; T*array;
};IN ARRAY.CPP
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <exception>
#include "A