¿Declarar una función que devuelve una matriz 2D en un archivo de encabezado?

I am trying to declare, within my header file, a function that returns a 2D array. How can this be accomplished, given that we already know the size of the array? Below is what I'm currently doing.

class Sample
{
public:
    char[x][y] getArr();
    void blah(int x, int y);
private:
    const static int x = 8;
    const static int y = 2;
    char arr[x][y];
};

preguntado el 08 de enero de 11 a las 21:01

5 Respuestas

It turns-out my original answer was totally incorrect, but I can't delete it since it's been accepted. De Digital XNUMXk separado respuestas below, I was able to compile this:

class Sample
{
    const static int x = 8;
    const static int y = 2;
public:
    typedef char SampleArray[x][y];

    SampleArray& getArr();
    void blah(int x, int y);

private:
    SampleArray arr;
};

Sample::SampleArray& Sample::getArr ()
{
    return arr;
}

(I had compiled my original solution only with the OP's given class declaration, not the definition of getArr().)

Just return a pointer to a pointer.

char** getArr();

contestado el 23 de mayo de 17 a las 14:05

@Fred and @Johannes Ugh, thanks for pointing that out. I've corrected the answer and converted it to community wiki. - Chrisaycock

I think you should use a typedef.

    typedef char TArray[2][2];
    TArray& getArr();

Respondido el 09 de enero de 11 a las 00:01

Arrays are not first-class citizens in C++. Please use boost::array (o std::array in C++0x) instead. It will behave much more like you want it to behave.

Respondido el 09 de enero de 11 a las 01:01

In C++, an array itself cannot be returned from a function directly. Alternatively, you can return a reference to an array, or a pointer to an array. So, you can write as:

char (&getArr())[x][y] { return arr; }

or

char (*getArr())[x][y] { return &arr; }

Espero que esto ayude.

Respondido el 09 de enero de 11 a las 00:01

Utilizar typedef. - Fred Nurk

Yup, a pointer to a pointer is the way to go. It's really hard to think about. I recommend you do a memory map on a piece of paper just to understand the concept. When I was taking C++ classes I decided I wanted functionality just like you are suggesting, after a lot of time, I drew a map of all the memory I needed and it dawned on me I was looking at a pointer to a pointer. That blew me away.

Respondido 08 Jul 12, 01:07

While it may make the most sense to return the array data member given, this question is vaguely worded: all these downvotes are unwarranted. This is still good advice in general, even if I disagree with emphasis on manual memory management. - Fred Nurk

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.