Declaring a function that return a 2D array in a header file?

自作多情 提交于 2019-12-02 13:32:07

问题


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];
};

回答1:


It turns-out my original answer was totally incorrect, but I can't delete it since it's been accepted. From two separate answers 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();




回答2:


I think you should use a typedef.

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



回答3:


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




回答4:


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; }

Hope this helps.




回答5:


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.



来源:https://stackoverflow.com/questions/4636144/declaring-a-function-that-return-a-2d-array-in-a-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!