Re: [ROOT] Operator overloading [silly question]

From: Ashley Cambrell (ash@freaky-namuh.com)
Date: Fri Apr 26 2002 - 16:22:24 MEST


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
>>
>>
>>    
>>
>
>  
>



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