Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!ames!sgi!mtoy@xman.SGI.COM From: mtoy@xman.SGI.COM (Michael Toy -- The S.G.I. XMAN) Newsgroups: comp.lang.c++ Subject: Re: matrix types and [] overloading Summary: sample implementation with a paramterized type Keywords: matrix, [] overloading Message-ID: <20863@sgi.SGI.COM> Date: 21 Oct 88 02:59:20 GMT References: <5181@saturn.ucsc.edu> Sender: daemon@sgi.SGI.COM Organization: Silicon Graphics, Inc., Mountain View, CA Lines: 45 In article <5181@saturn.ucsc.edu>, (Robert Skinner) writes: > I'm constructing a general 2d Matrix object for a class I'm now taking > on matrix computations. It would be nice if I could > overload the [] operator ... > --------------------------- File Matrix.h -------------------------------- // // Generic class for 2D matrices of any type with runtime sizing // #define MatrixDeclare(type) \ class MatrixOf/**/type {\ type* data;\ int ncols; \ public:\ MatrixOf/**/type() \ { data = 0; } \ MatrixOf/**/type(int rows, int cols) \ { ncols = cols; data = new type[rows * cols]; } \ type* operator[](int row)\ { return data + row*ncols; }\ ~MatrixOf/**/type()\ { if (data) delete data; }\ } #define Matrix(type) MatrixOf/**/type --------------------------- End File main.c++ -------------------------------- To define a type for a matrix of "FROB"'s, just do: #include "Matrix.h" MatrixDeclare(FROB) To get a m by n matrix of FROBS do: Matrix(FROB) my_matrix(m, n); now both "my_frob = my_matrix[2][3]" and "my_matrix[2][3] = my_frob" should work. -- From the mixed up files of Mr. Michael C. Toy Internet: mtoy@SGI.COM UUCP: {ames,ucbvax,decwrl,sun,parcvax}!mtoy