C++ Class Problem

Started by
3 comments, last by Punx 21 years, 11 months ago
One of my classes (for this example Class1) uses an object of another class (Class2) as a parameter for a method. When I try to compile I get: error C2061: syntax error : identifier ''Class2'' So I thought to fix this problem I would add... #include "class2.h" to ''Class1.h''. But now whenever I compile I get an error saying: error C2011: ''Class2'' : ''class'' type redefinition I know I''m doing something wrong but I don''t know how to correct it.
~punx
Advertisement
you need to put #ifndef into your code


  //class1.h#ifndef CLASS1#define CLASS1// your code here#endif  


this tells the compiler that if it has already included this section of code, not to do it again (redefinition)

cyn

EDIT - fixed source tags

[edited by - cyn on May 5, 2002 11:02:23 PM]
It''s a FAQ.

class1.h
#ifndef CLASS1_HEADER#define CLASS1_HEADERclass class2; // declare class2class class1  // define class1{   // can now use class2 (only) as return type,    // parameter, pointer or reference.}#endif 


class2.h
#ifndef CLASS2_HEADER#define CLASS2_HEADERclass class1; // declare class1class class2  // define class2{   // can now use class1 (only) as return type,    // parameter, pointer or reference.}#endif 


Your source (.cc, .C, .cpp, .cxx ...) files will still need to include both class1.h and class2.h

[Questions (STFW) | GDNet Start Here | GDNet Search | Forum FAQ | Google | Asking Smart Questions ]
[Docs (RTFM) | MSDN | SGI''s STL | OpenGL | File formats]
[C++ Must Haves (RTFS) | MinGW | Boost | Loki | FLTK | SDL ]

Stolen from Magmai Kai Holmlor, who held it from Oluseyi, who was inspired by Kylotan...
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
This article might help you:

http://www.gamedev.net/reference/programming/features/orgfiles/
---visit #directxdev on afternet <- not just for directx, despite the name
cyn: he''s got a recursive definition problem, not just a multiple header inclusion problem.

There is an article by Kylotan there.
Go study it and you will be enlightened

[Questions (STFW) | GDNet Start Here | GDNet Search | Forum FAQ | Google | Asking Smart Questions ]
[Docs (RTFM) | MSDN | SGI''s STL | OpenGL | File formats]
[C++ Must Haves (RTFS) | MinGW | Boost | Loki | FLTK | SDL ]

Stolen from Magmai Kai Holmlor, who held it from Oluseyi, who was inspired by Kylotan...
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement