arrays - Custom index operator C++ -


i having trouble building class makes sure user not access element off end of array, building class mimics behavior of array, adds check. is, class create sequence of elements of given type, , allow access these elements [] bracket operator, check make sure user not try element doesn't exist.

here instructions on building it.

i have no idea how make index operator case. please me. thanks!

here 3 files have far...

dvd.h

class dvdarray{      dvd *elt;     int size;     static int defaultsieze;     int getsize();     void display();         dvdarray(unsigned int sz);     dvdarray();     dvdarray(dvdarray &obj);     ~dvdarray();  };  

dvd.cpp

dvd::dvd(){     id =0;     int n=5;      title = new char [n];     director = new char [n];        title[0] = '\0';      director[0] = '\0';  } dvd::~dvd(void) {  } dvdarray::dvdarray(unsigned int sz){     elt = new dvd[sz]; } dvdarray::dvdarray(){     size = defaultsieze;     elt = new dvd[defaultsieze];  } dvdarray::dvdarray(dvdarray &obj){      size = obj.size;     elt = new dvd[defaultsieze];     (int i=0; i!='\0'; ++i) {         elt[i]=obj.elt[i];          }  } dvdarray::~dvdarray(void) {  } 

the easiest / cleanest thing derive std::vector (or std::array if suits purposes better), safe long don't delete object using std::vector*, , long functions want checked access accept parameter checked_vector , not std::vector*/&...

example:

template <typename t> class checked_vector : public std::vector<t> {   public:     // ...forwarding constructors     using std::vector::vector;      t& operator[](size_t n) { return at(n); }     const t& operator[](size_t n) const { return at(n); } }; 

note: won't protect invalid use of iterators, such incrementing them far or adding illegal offset them.

if - whatever reason - you're determined use own implementation...

dvd& dvdarray::operator[](size_t n) {     if (n >= size)         throw std::runtime_error("invalid array index");     return dvd[sz]; }  const dvd& dvdarray::operator[](size_t n) const {     if (n >= size)         throw std::runtime_error("invalid array index");     return dvd[sz]; } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -