I've been looking for a good answer to this and I can't find one that seems satisfactory.
Suppose I have a function that reads a file, builds a house object, and passes that object to another function that will write the house to a file. The house object has, internally, a few integers to describe itself (like dimensions) and some vectors that holds other objects like chair or wall objects. When writing out to a file, the write function must get access to all the information about the house object. For the integers, that's pretty easy. When it comes to the vectors, though, I'm having trouble.
While I could return the vectors by copy or reference, I believe both options are not ideal. Usually, I return const_iterators and let write function to iterate through the vector at its own leisure while keeping it from changing the vector. This seems fine if I am using a vector of non-custom objects (string, int, etc...). However, if I make my own class and store that, AFAIK, in order for the calling function to get the return value, it must declare either a generic vector or include the custom class header files just so I can declare a vector of that class. Is there a better way to solve this problem?
For example, I normally do this if I use vectors of ints:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Foo
{
std::vector<int> v;
//Populate v.
std::vector<int>::const_iterator getStart() { return v.begin(); }
std::vector<int>::const_iterator getEnd() { return v.end(); }
}
int main()
{
foo way;
std::vector<int>::const_iterator itStart = way.getStart();
std::vector<int>::const_iterator itEnd = way.getEnd();
//Do something.
}
|
I have to do this when I use vectors of custom class objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
//Mojo.hpp
class Mojo
{
//Something.
}
//Foo.hpp
#include "Mojo.hpp"
class Foo
{
std::vector<Mojo> v;
//Populate v;
std::vector<int>::const_iterator getStart() { return v.begin(); }
std::vector<int>::const_iterator getEnd() { return v.end(); }
}
//Main.cpp
#include "Mojo.hpp"
#include "Foo.hpp"
int main()
{
Foo way;
std::vector<Mojo>::const_iterator itStart = way.getStart();
std::vector<Mojo>::const_iterator itEnd = way.getEnd();
//Do something.
}
|
Thanks in advance.