Re: [ROOT] Operator overloading [silly question]

From: Fons Rademakers (Fons.Rademakers@cern.ch)
Date: Fri Apr 26 2002 - 16:58:42 MEST


Hi Ashley,

 for td["jane"] = "anderson"; to work you need something like:


TString &THTTPMap::operator[](const char *key)
{
   TObjectString *value = (TObjString*)FindObject(key);
   if (!value)
      value = new TObjString;
      Add(new TObjString(key), value);
   }
   return value->String();
}


Cheers, Fons.




On Fri, 2002-04-26 at 16:22, Ashley Cambrell wrote:
> Hi Stephen,
> 
> Stephen J. Gowdy wrote:
> 
> >You'd make this one;
> >
> >const TString& operator[]( const char* key ) const;
> >
> >and then create a new one;
> >
> >TString& operator[]( const char* key );
> >  
> >
> td["jane"] = "anderson";
> 
> How do I get the value on the right side of the equals sign? ie
> "anderson".  "jane" comes across on key?
> 
> Wouldn't it need to be something like:
> 
> void operator[]( const char* key , const char* value)
> {
> 	Add(key, value);
> }
> 	
> void Add(const char* key, const char* value)
> {
> 	TObjString *tosKey = new TObjString(key);
> 	TObjString *tosValue = new TObjString(value);
> 
> 	if( !this->TMap::GetValue(tosKey) )
> 	{
> 		this->TMap::Add(tosKey, tosValue);
> 	}
> 	else
> 	{
> 		TObjString *oldVal = this->TMap::Remove(tosKey);
> 		delete oldVal;
> 		this->TMap::Add(tosKey, tosValue);
> 	}
> }
> 
> or some such thing?  
> 
> Thanks Stephen :-)
> 
> Ashley Cambrell
> 
> >On Fri, 26 Apr 2002, Ashley Cambrell wrote:
> >
> >  
> >
> >>Hi Rooters,
> >>
> >>Just a simple question.  I'm still learning so I'm sorry if this is one
> >>of those "What's an int?" questions.  I have a class the inherits from
> >>TMap and I want to emulate associative arrays.  
> >>
> >>I have this:
> >>
> >>    TString operator[](const char* key)
> >>    {
> >>        TObjString *tosKey = new TObjString(key);
> >>        TString value;
> >>       
> >>        if( this->TMap::GetValue(tosKey) )
> >>            value = ((TObjString
> >>*)(this->TMap::GetValue(tosKey)))->String();
> >>       
> >>        delete tosKey;
> >>       
> >>        return value;
> >>    }
> >>root [1] THTTPData td;                                         
> >>root [2] td.Add(new TObjString("bob"), new TObjString("smith"));
> >>root [3] cout << td["bob"] << endl;                            
> >>smith
> >>root [4]
> >>
> >>which works fine, but I'd like to also be able to do
> >>
> >>td["jane"] = "anderson";
> >>
> >>Is it possible?  (add another operator overload? but then how does C++
> >>tell the difference between the two)
> >>
> >>Thanks for your patience :-)
> >>
> >>Ashley Cambrell
> >>
> >>
> >>    
> >>
> >
> >  
> >
> 
> 
-- 
Org:    CERN, European Laboratory for Particle Physics.
Mail:   1211 Geneve 23, Switzerland
E-Mail: Fons.Rademakers@cern.ch              Phone: +41 22 7679248
WWW:    http://root.cern.ch/~rdm/            Fax:   +41 22 7679480



This archive was generated by hypermail 2b29 : Sat Jan 04 2003 - 23:50:51 MET