Declaring a function that return a 2D array in a header file?
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];
};
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.
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();
精彩评论