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

女生的网名这么多〃 提交于 2019-12-02 03:50:12
chrisaycock

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();

I think you should use a typedef.

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

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.

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.

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.

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