🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.g++
Article #438

operator[][]?

#438
From: Michael Tiemann
Date: Tue, 16 May 1989 00:11
53 lines
1984 bytes
   I  am trying to  determine what support there  is in C++  for multi-dimensional
   arrays within a class. For example, the following class  definition attempts to
   implement an array of pointers  to vectors.   Now, I  know that  I can overload
   operator[],  but  what I would really  like to be able  to  do  is overload the
   ficticious  operator[][]. How can  I achieve  this  functionality? Am I missing
   something very obvious?

	   typedef int Type
	   
	   class C {
	   private:
	     int r, c;
	     Type** data;
	   public:
	     X (int row, int col) {
	       this->r = row; this->c = col;
	       this->data = new Type* [row];
	       for (int i = 0; i < col; i++)
		 this->data[i] = new Type [col];
	     }
	   
	     ~X () {
	       for (int i = 0; i < r; i++)
		 delete this->data[i];
	       delete this->data;
	     }
	   
	     inline Type* operator[] (int row) {
	       return this->data[row];
	     }
	   
	     inline Type& operator[][] (int row, int col) {
	       return this->data[row][col];
	     }
	   };

You are missing something obvious: you need two kinds of types, a row
type and a matrix type.  matrix::operator[] can return a row&, and
row::operator[] can return whatever scalar type interests you.  Then,
when you say

   mat[row][col] = 5;

this is translated into

   row_tmp& = mat[row];
   row_tmp[col] = 5;

This is how you cascade operator[], or more generally, any pair of
operators.

Michael
Technical Details
Message-ID: <8905160011.AA10572@yahi.stanford.edu>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!YAHI.STANFORD.EDU!tiemann
References: <NEATH.89May15154230@solar-1.stars.flab.Fujitsu.JUNET>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!YAHI.STANFORD.EDU!tiemann
From: tiemann@YAHI.STANFORD.EDU (Michael Tiemann)
Newsgroups: gnu.g++
Subject: operator[][]?
Message-ID: <8905160011.AA10572@yahi.stanford.edu>
Date: 16 May 89 00:11:45 GMT
References: <NEATH.89May15154230@solar-1.stars.flab.Fujitsu.JUNET>
Sender: daemon@tut.cis.ohio-state.edu
Reply-To: tiemann@lurch.stanford.edu
Distribution: gnu
Organization: GNUs Not Usenet
Lines: 53