I'm trying to overload the [] operator, so I made a simple vector class. I was looking through some of the directx headers and how they overloaded the operator. I made a completely const version that returns the value at a certain pos, and a non-const one that returns a pointer to a pos in the array (I think...) Anyway, it sorta works. On my machine it prints V[1] as 15 and V[0] as 34, but the program always crashes and I'm not sure why. Any help would be great, thanks!
Here's the code:
Code:
#include <iostream.h>
class CVect
{
private:
int *dat;
int len;
public:
CVect ();
CVect (int);
CVect (CVect&);
~CVect () {};
const int operator [] (int) const;
int get_len (void) const;
int& operator [] (int);
void set_len (int);
};
const int CVect::operator [] (int a) const {
return dat [a];
}
int& CVect::operator [] (int a) {
return *(dat + (a * sizeof (int)));
}
inline int CVect::get_len (void) const {
return len;
}
inline void CVect::set_len (int l) {
len = l;
}
CVect::CVect () : len (1)
{
dat = new int (len);
}
CVect::CVect (int l) : len (l)
{
dat = new int (l);
}
int main (void)
{
CVect V (10);
V[1] = 16;
V[0] = 34;
for (int i = 0; i < V.get_len() - 1; ++i)
cout << V[i] << endl;
return (0);
}