简体   繁体   English

在C ++中返回指向const数组的指针

[英]Return pointer to a const array in c++

I have to 2 constant arrays in header files, say 我必须在头文件中有2个常量数组

const TPair<char, char> array1[] =
{
    {'V', rV},      
    {'v', rv},
    {'H', rH},
    {'h', rg},
    {0, 0}
};

and array2 similar to array1. 和array2类似于array1。
Now I need a function that will choose one of these arrays and return pointer to appropriate array. 现在,我需要一个可以选择这些数组之一并返回指向适当数组的指针的函数。
How should signature of this function look like? 该函数的签名应如何显示? And what do I return: array1 or array1&? 我该返回什么:array1或array1&?

typedef s make this kind of code much more readable: typedef使这种代码更具可读性:

typedef TPair<char, char> pair_of_chars;

Then, ... 然后, ...

const pair_of_chars array1[] =
{
    // [...]
};

Your choosing function may look a bit like this: 您的选择功能可能看起来像这样:

const pair_of_chars* choose(int number)
{
    if (number == 1)
    {
        return array1;
    }
    return array2;
}

This a bit tricky. 这有点棘手。 To start with, you don't want to put the definition of the array in the header. 首先,您不想将数组的定义放在标题中。 This results in an instance of the array in every translation unit which includes the header, most of which will never be used. 这将在每个包含标题的转换单元中生成一个数组实例,其中大多数将永远不会使用。 And I'd definitly use a typedef. 而且我会明确使用typedef。 If the only way you access this array is through the return value of the function you ask about, then all you need in the header is a declaration for the function: 如果访问此数组的唯一方法是通过询问的函数的返回值,那么标头中所需的就是该函数的声明:

typedef TPair <char, char> CharPairArray[3];
CharPairArray const& getArray( bool condition );

(Without the typedef, the function declaration is: (没有typedef,函数声明为:

TPair <char, char> const (&getArray( bool condition ))[3];

This is a route you don't want to go.) 这是您不想走的路线。)

If you also need to access the arrays otherwise, you need to add: 如果还需要访问数组,则需要添加:

extern CharPairArray const array1;
extern CharPairArray const array2;

Then, is some source file (only one), you define the functions and the arrays: 然后,是一些源文件(只有一个),您可以定义函数和数组:

CharPairArray const array1 = { /* ... */ };
CharPairArray const array2 = { /* ... */ };

CharPairArray const&
getArray( bool condition )
{
    return condition ? array1 : array2;
}

If you don't use the extern in the header, you can put the actual arrays in an unnamed namespace. 如果在标题中不使用extern ,则可以将实际的数组放在未命名的名称空间中。

Its type should be: 其类型应为:

const TPair<char, char>*

and you should return 你应该回来

array1

Like this: 像这样:

const TPair<char,char>* choose() {
    return condition ? array1 : array2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM