--- In [email protected], xcianox2...@... wrote:
> Hi all,
> IÂ tried to use STL for a C++ class that can contain
> arrays of itself as, for example, a directory tree.
Not sure what the little Â's are. I would say your email
client is inserting them (and other characters.)
> It is easy to implement this using normal pointers but
> I tried to use the std::vector container and got compile
> errors. The following is a code fragment:
> Â
> #include <vector>
> #include <string>
> // forward declaration
> class DirectoryEntryArray;
Here you declare a class called DirectoryEntryArray.
> // describes a single directory entry: the name, the size,
> etc.. and
> // the type of the entry: it could be a subdirectory
> class DirectoryEntry
> {
> public:
>  std::string m_name;
>  int m_size;
>  std::string m_dateCreated;
>  int m_type; // 0=FILE, 1=LINK, 2=DIRECTORY, ...
> Â // if m_type == DIRECTORY the entry contains an array of
> other entries
> Â // we need a pointer because the array has an incomplete
> type
>  DirectoryEntryArray *m_array;
> };
> typedef std::vector<DirectoryEntry>Â DirectoryEntryArray;
Here you declare DirectoryEntryArray to be a synonym of another
class (std::vector<>).
Simpler is...
typedef std::vector<class DirectoryEntry> DirectoryEntryArray;
class DirectoryEntry
{
...
DirectoryEntryArray *m_array
};
Even simpler is...
class DirectoryEntry
{
...
std::vector<DirectoryEntry> *m_array;
};
Even simpler still is...
class DirectoryEntry
{
...
std::vector<DirectoryEntry> m_array;
};
You don't really need pointers at this stage.
<snip>
> The code does not compile on my linux machine GCC 4.0.3.
> Here is the error:
> Â
> test.cpp:27: error: conflicting declaration âtypedef
> class std::vector<DirectoryEntry, std::allocator
> <DirectoryEntry> > DirectoryEntryArrayâ
> test.cpp:10: error: âstruct DirectoryEntryArrayâ has
> a previous declaration as âstruct DirectoryEntryArrayâ
This actually tells you that you've defined the same name
for two different classes.
> ...I think the code is surely wrong but do not undestand
> why is it wrong.
Because a forward declaration of a class name declares that
class. Attempting to then typedef it as a synonym for a
different class is not allowed.
What you've done is similar to...
class A; // declare a class called A
class B; // declare a class called B (think std::vector<>)
typedef B A; // somehow redeclare class A to be class B?!
--
Peter