[英]C++ returning an array of objects from a class method
I am trying to return a two dimensional array of 'room' objects as a kind of print/display of what's in the array. 我试图返回“房间”对象的二维数组,作为数组内容的打印/显示。
Room* m_map[10][10];
generated like so: 生成如下:
//Initialise array to NULL
for(int x=0;x<10;x++)
{
for(int y=0;y<10;y++)
m_map[x][y] = NULL;
}
for(int n=0; n<10; n++)
{
for(int ran=0; ran<3; ran++)
{
int r_n = rand() % 10 ;
Room* r = new Room(n, "Normal", true, false, false, true);
m_map[r_n][n] = r;
}
}
So what this gives is a scatter of Rooms in the array. 因此,这给出的是阵列中房间的散布。
I'd then like to display/print for the user where these rooms are, in reference to the NULL. 然后,我想参考NULL为这些房间显示/打印给用户。
So I could for example if NULL display '#', if it's a Room Leave a ' '. 因此,例如,如果是NULL,则显示NULL。
I'm unsure of the bit I should return in the method. 我不确定应该在方法中返回什么。
Any help or pointing in the right direction would really be appreciated 任何帮助或指向正确的方向,将不胜感激
It would be easier to use an std::array<Room, N>
if the array is fixed size (and the size is known at compile time), or an std::vector<Room>
if it isn't. 如果数组为固定大小(并且在编译时已知大小),则使用std::array<Room, N>
会更容易std::array<Room, N>
如果不是固定大小,则使用std::vector<Room>
更容易。
#include <array> // or <tr1/array> if no C++11
std::array<Room, TheSize> returnArray() const
{
return m_map;
}
Be careful though, depending on the use-case, you might want to return a reference, not a copy: 但是要小心,根据用例,您可能要返回引用而不是副本:
const std::array<Room, TheSize>& returnArray() const
{
return m_map;
}
That said, if all you want to do is print some objects, then don't expose implementation details such as the array. 就是说,如果您只想打印一些对象,则不要公开实现细节,例如数组。 You can either provide a print function ot, better still, override std::ostream& operator<<
for your type. 您可以提供打印功能ot,更好的是,为您的类型覆盖std::ostream& operator<<
。
// inside your class declaration:
friend
std::ostream& operator<<(std::ostream& o, const MyClassWithRooms& r)
{
// loop over r.m_map and print to o
}
Edit If the array is 2D (as mentioned in comments) then there are options: a nested array structure ( std::array<std::array<T,N>,M>
, or a "flat" N*M
array, and some careful playing with indices). 编辑如果数组是2D(如注释中所述),则有以下选项:嵌套数组结构( std::array<std::array<T,N>,M>
或“平面” N*M
数组,以及一些谨慎地使用索引)。
Edit 2 : If you need to store things that can be either set or not, you could use arrays or vectors of std::unique_ptr<Room>
instead of plain old Room
s of raw Room*
. 编辑2 :如果需要存储可以设置的对象,则可以使用std::unique_ptr<Room>
数组或向量,而不是raw Room*
的普通Old Room
。 Another option is simply to use a 2D map, an std::map<int, std::map<int, Room>>
. 另一种选择是简单地使用2D地图,即std::map<int, std::map<int, Room>>
。
Easiest way to do it is to use a std::vector< Room >
for your array. 最简单的方法是对数组使用std::vector< Room >
。 That way you don't have to worry about memory management, and the size is built into the array. 这样,您不必担心内存管理,并且大小内置在阵列中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.