Re: Recursive Classes
"Luigino" <npuleio@rocketmail.com> ha scritto nel messaggio
news:c70872d1-2c64-4671-a61f-0b91e67994d1@s15g2000yqs.googlegroups.com...
<mainnode>
<module name="mymodule1">
<sentence name="mysentence1">
<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
("mysentence1")->Row("myrow3")->GetValue("description");
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.
class CRow
{
public:
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:
class CSentence
{
public:
// 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 ];
}
...
private:
// 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.
class CModule
{
public:
CSentence * Sentence( LPCTSTR sentenceName )
{
... check that sentenceName is in the collection
// Return required sentence
return m_sentences[ sentenceName ];
}
private:
// 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.
HTH,
Giovanni