Re: Intit an Array of objects with ctor
peterfarge <peterfarge@gmx.de> wrote:
I need a hint: I want to create a game map. Every place on this map is
a PlaceClass. This PlaceClass has one ctor with a pointer to a init
object. Now I want to create my map as a 2D of PlaceClass
class Map {
public::
Map(cInit *ptrInitObj) : m_map[100][100](ptrInitObj) { // <-- How to
init the array?
}
private:
PlaceClass m_map[100][100];
};
I would do it more like this:
// see "The C++ Programming language" section 24.3.7.2 for other options
inline void Assert(bool pred, const char* file, int line) {
if (!pred) {
std::stringstream ss;
ss << "logic error at: " << line << "in file: " << file;
throw std::logic_error(ss.str());
}
}
class cInit { };
class PlaceClass {
public:
PlaceClass(const cInit& initObj);
};
class Map {
std::vector<PlaceClass> m_map;
PlaceClass& at(int x, int y) {
Assert(0 <= x && x < 100, __FILE__, __LINE__);
Assert(0 <= y && y < 100, __FILE__, __LINE__);
return m_map[y + x * 100];
}
public:
Map(const cInit& initObj): m_map(1000, PlaceClass(initObj)) { }
};
Now, instead of "m_map[x][y]" inside the code, do "at(x, y)". Note that
the 'at' function is private so that encapsulation is not broken.