Hey guys ive created an overload bracket operator. For some reason I had to create an initialize function to set the array value. After it is set, the overloaded operator works fine. I would like to fix the operator so I didnt have to call an addation function before I use it. Here is my code.
The implamentation file is empty because all the function are template related.Code:#ifndef ASSOCARRAY_H #define ASSOCARRAY_H #include <iostream> #include <cstdlib> #include <string> using namespace std; template < class T > class AssocArray { struct data { T value; string index; }; public : AssocArray(int size); AssocArray(const AssocArray &object); ~AssocArray(); T &operator[](const string &cell); void initialize(const string &cell, T input); private: data *ptr; int total; int arraySize; }; /* ===================================== */ template< class T > /* default AssocArray constructot */ AssocArray < T > ::AssocArray(int inSize) { total = 0; arraySize = inSize; ptr = new data[arraySize]; } template< class T > /* AssocArray copy constructor */ AssocArray < T > ::AssocArray(const AssocArray &object) { total = object.total; arraySize = object.arraySize; ptr = new data[arraySize]; for (int count = 0 ; count < arraySize ; count++) *(ptr + count) = *(object.ptr + count); } template< class T > /* AssocArray destructor */ AssocArray < T > ::~AssocArray() { } template< class T> /* initialize values */ void AssocArray < T > ::initialize(const string &cell, T input) { ptr[total].index = cell; ptr[total].value = input; total++; } template< class T > /* Overloaded bracket operator */ T &AssocArray < T > ::operator[](const string &cell) { if (cell == "") { cout<<"no room"<<endl; exit(1); } else { for (int count = 0 ; count < arraySize ; count++) { if (ptr[count].index == cell) return (ptr[count].value); } exit(1); } } #endif
My main looks like this....
If anyone see where I can change it so I can get rid of initialize function let me know.Code:#include <iostream> #include "AssocArray.h" using namespace std; int main(int argc, char *argv[]) { /* Create three different data type */ typedef AssocArray< int > intclass; intclass age(2); age.initialize("chris",21); age["chris"]=25; cout << age["chris"] << endl; return 0; }
Thanks a lot.



LinkBack URL
About LinkBacks


