Fog Creek Software
Discussion Board




C++ question

My email server is currently down, so I don't have access to newgroups. I thought I'd post this here to see if there are any C++ wizzes out there that can help.  I have a class, Array2D which contains a proxy class Array1D.  This allows the use of normal array syntax in code.  The problem is when instantiating an Array2D object on the heap I can't access the elements of the array using ->.  The level of indirection seems to be incorrect. Any help or hints would be appreciated.

#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct {
int a, b;
} c;

template <class T>
class Array2D {
    public:        
    class Array1D {
    private:
        T *cols;            
    public:
    Array1D(int n_cols = 0)
    {
    cols = new T[n_cols];
              memset((void *)cols, 0x0000, (n_cols * sizeof(T)));
    }
        
    ~Array1D(void)
    {
    delete [] cols;
    }    

    T& operator[] (int index)
    {
    return cols[index];    
    }
                
    const T& operator[] (int index) const
    {
    return cols[index];
    }
    };

    private:
        
    Array1D **rows;    

    public:

    Array2D(int n_rows = 0, int n_cols = 0)
    {            
        rows = new Array1D *[n_rows];
        for (int i = 0; i < n_rows; i++)
        rows[i] = new Array1D(n_cols);
    }

    ~Array2D(void)
    {
        delete [] rows;
    }

    Array1D& operator[] (int index)
    {
        return *rows[index];
    }
        
    const Array1D& operator[] (int index) const
    {
        return *rows[index];
    }
};

int main(int argc, char *argv[])
{
Array2D<c> a(2,2);  // 2D object
Array2D<c> *v = new Array2D<c>(2,2);  // on heap
int t;

a[0][0].b = 2; // works fine
a[1][1].a = 5; // works fine
a[0][1].b = 7; // works fine
t = a[0][1].a; // works fine

//****************************************
// Does not compile ?
// v[0][0]->a = 1;
//****************************************

cout << a[0][0].b << a[1][1].a << t << endl;
    
delete [] v;

return 1;
}

Just some dude
Saturday, January 11, 2003

Try:

(*v)[0][0].a

The first method you are invoking is the operator[] on v

v[0] would treat v as a pointer to an array of Array2D objects.

Just another dude
Saturday, January 11, 2003

You have an operator[] member function for the Array2D class, but are trying to call it on a pointer to Array2D.  Dereference v to get an Array2D object.

mackinac
Saturday, January 11, 2003

Thanks dudes.  Now to get that delete [] v working heh.

Just some dude
Saturday, January 11, 2003

Nm. . . should'nt be delete [] v; should be delete v; o_O; And life is good :)

Just some dude
Saturday, January 11, 2003

*  Recent Topics

*  Fog Creek Home