Re: Recursive Classes
"Luigino" <firstname.lastname@example.org> ha scritto nel messaggio
<row name="myrow1" description="..."/>
<row name="myrow2" description="..."/>
and I'd like to code the class to have like:
CString description = MyTinyXML->Module("mymodule2")->Sentence
How I would implement a class to have a behavior like this?.... I
guess it'd be a recursive class maybe...
You could define a class CRow, with a method GetValue which takes a string
as input and returns a string, e.g.
CString GetValue( LPCTSTR valueName ) const;
You could use a map (like std::map or CMap or your preferred map container
class) to associate 'description' to the actual description string value
(read from XML file), and do the same for other attributes of the <row> node
(like 'name' etc.).
Then you could build a class CSentence, which stores a collection of
instances of CRow's inside.
And you could expose a public method 'Row' like this:
// Access the row with specified name
CRow * Row( LPCTSTR rowName )
// Check that rowName is in the m_rows collection
// Returns pointer to specified row
return m_rows[ rowName ];
// Collection of CRow's.
// Can use a map from string (row name) to CRow pointer
std::map< CString, CRow * > m_rows;
Then you could define a class CModule, which stores a collection of
CSentence's, and expose a method 'Sentence' to access sentence by name.
CSentence * Sentence( LPCTSTR sentenceName )
... check that sentenceName is in the collection
// Return required sentence
return m_sentences[ sentenceName ];
// Assocaite sentence name with CSentence pointer
std::map< CString, CSentence * > m_sentences;
And so on for other node in your XML structures.
Then you could write something like myModule->Sentence(
_T("sentence1" )->Row( _T("row2") )->GetValue( _T("description") );
You can build those data structures while processing your XML file.
You should pay attention to properly free heap allocated memory, and a
possible solution is to use std::/boost:: shared_ptr (or your preferred
smart pointer template class) instead of raw pointers.