Struct in a separate header file causing problems in C ++

I have a struct Tree that is defined inside Class Parser . I have methods defined in Parser that accept Tree as input.

 void Parser::InputTree(const Tree& input) { //uses data from Tree } 

Everything seemed to be working fine. But then I had to use Tree outside the class. So I decided to define a struct Tree in a separate header. I have included this header in the header file for Parser . Although I see no errors in the Parser header file, the source file shows errors on my Eclipse. Says no member declaration was found, pointing to the InputTree method.

My question is: first, is this the right strategy to define the structure in a separate header? Secondly, what am I doing wrong? Thirdly, I have some types of enum that I want to use for different classes. Where to define it?

+4
source share
3 answers

Right structure:

parser.h

 #ifndef _PARSER_H_ #define _PARSER_H_ #include "tree.h" class Parser { void InputTree(const Tree& input); }; #endif /*_PARSER_H_*/ 

parser.cpp

 #include "parser.h" void Parser::InputTree(const Tree& input){ // use data from Tree } 

tree.h

 #ifndef _TREE_H_ #define _TREE_H_ struct Tree { //nodes }; #endif /*_TREE_H_*/ 

Inclusion of parser.h includes tree.h and therefore struct Tree is available in the main compilation unit.

+3
source

The simple rule of thumb that I usually follow is that if a user-defined data type (i.e. struct, enum, etc.) is used only inside the class, I end up defining this data type in the class definition.

But if the same type needs to be used for two or more classes (without any relationship between parents and children), I end up defining the type either in another header file, or usually in the namespace (when the types are or related to some mod).

And yes, you could use several such namespaces in several header files (to group related types) if you feel the need to distinguish them, but I just show a simpler example using one namespace:

/ * MyNamespace.h * /

 #ifndef MY_NAMESPACE_H #define MY_NAMESPACE_H namespace MyNamespace { struct Tree { int a; char b; }; enum SomeEnum { VALUE_0 = 0, VALUE_1 = 1, VALUE_2 = 2 }; } #endif 

/ * Parser.h * /

 #ifndef PARSER_H #define PARSER_H #include "MyNamespace.h" class Parser { public: void InputTree(const MyNamespace::Tree& input); }; #endif 

/ * Parser.cpp * /

 #include "Parser.h" void Parser::InputTree(const MyNamespace::Tree& input) { } 
+3
source

Yes, this is the right strategy to define the structure in a separate header file.

What you are doing wrong is difficult to say without entering additional data, but this is probably due to inclusion, inclusion-protection, or namespace mismatches.

And finally, you must declare the listings in another header file with the proper inclusion of the guards.

+2
source

All Articles