Re: [ROOT] Operator overloading [silly question]

From: Stephen J. Gowdy (gowdy@SLAC.stanford.edu)
Date: Fri Apr 26 2002 - 21:18:25 MEST


Fons gave you the implementation. A reference to the string in the 
dictionary is passed back and then that string is updated to contain the 
new value.

On Sat, 27 Apr 2002, 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
> >>
> >>
> >>    
> >>
> >
> >  
> >
> 
> 
> 

-- 
 /------------------------------------+-------------------------\
|Stephen J. Gowdy                     | SLAC, MailStop 34,       |
|http://www.slac.stanford.edu/~gowdy/ | 2575 Sand Hill Road,     |
|http://calendar.yahoo.com/gowdy      | Menlo Park CA 94025, USA |
|EMail: gowdy@slac.stanford.edu       | Tel: +1 650 926 3144     |
 \------------------------------------+-------------------------/



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