I'm trying to write a program like so:
I have a cpp file I waould like to run and create objects of 2 classes.
Each class has a field of the other class.
I can't seem to solve this after a lot of trials and searches.
Can anyone help?
added the code:
* Created on: Nov 4, 2012
* Author: achie
In file included from src/../include/Class1.h:13:0,
src/../include/../include/Class2.h:23:28: error: ‘Class1’ was not declared in this scope
src/../include/../include/Class2.h:23:34: error: template argument 1 is invalid
src/../include/../include/Class2.h:23:34: error: template argument 2 is invalid
src/../include/../include/Class2.h:26:9: error: ‘Class1’ was not declared in this scope
src/../include/../include/Class2.h:26:15: error: template argument 1 is invalid
src/../include/../include/Class2.h:26:15: error: template argument 2 is invalid
src/Class1.cpp: In constructor ‘Class1::Class1(int, std::vector<Class2>)’:
src/Class1.cpp:11:1: warning: ‘Class1::number’ should be initialized in the member initialization list
src/Class1.cpp:11:1: warning: ‘Class1::Class2Classes’ should be initialized in the member initialization list
#2 Try editing you code (it there were lines numbers, as there would be if the code was tagged...) so the header files just forward declare the other class.
in Class1.h and similarly for Class2.h
Then edit your cpp file the other way round (it is unusual to see a forward definition for a class in a cpp file rather than the header, it it exists).
PS Note that the above (probably) works as vector<> uses a pointer to your classes internally. (The probably is because I don't know the behavior of all implementations of vector)
This trick would not work if you'd used a C-style array as the compiler would then have to see the complete class declaration up front before working out how to layout memory for the variables which use your class. When it's a pointer, the compiler already knows the size of a pointer, so it works ok. It's happy to wait until you first use the pointer.