用于访问指针数组的C ++指针声明

时间:2016-04-01 07:46:30

标签: c++ c pointers

我需要有关指针声明的帮助,我有几个带有指针数组的类,例如。

const char* const clsMainWin::mcpszXMLattrRoot[] = {"bottom","left","right","top",NULL};
const char* const clsMainWin::mcpszXMLattrA[] = {"x","y","z",NULL};

我想要做的是定义一个指针,该指针对上面的指针数组进行分组,允许我选择一个带有单个索引的约会,例如:

const char* const allOptions[] = {mcpszXMLattrRoot, mcpszXMLattrA};

其中:

allOptions[0][...] would be used to access mcpszXMLattrRoot and its contents:
allOptions[1][...] would be used to access mcpszXMLattrA and its contents

然而到目前为止,我正在努力使allOptions的声明正确。

3 个答案:

答案 0 :(得分:2)

您可以存储mcpszXMLattrRootmcpszXMLattrA的指针(即const char * const *

const char* const * allOptions[] = {mcpszXMLattrRoot, mcpszXMLattrA};

答案 1 :(得分:2)

static const char* const a[] = {"a1", "a2", "a3"};
static const char* const b[] = {"b1", "b2", "b3", "b4"};
static const char* const* const z[] = {a, b};

z的类型有一个额外的*,因为它是一个指向char指针数组的指针数组。

在后者const之前需要*,因为ab是常量。没有恒定,它将是:

static const char* a[] = {"a1", "a2", "a3"};
static const char* b[] = {"b1", "b2", "b3", "b4"};
static const char** z[] = {a, b};

您可以使用constexpr

在课堂上初始化它
class Foo {
    static constexpr const char* const a[] = {"a1", "a2", "a3"};
    static constexpr const char* const b[] = {"b1", "b2", "b3", "b4"};
    static constexpr const char* const* z[] = {a, b};
};

或者是课外:

class Foo {
    static const char* const a[];
    static const char* const b[];
    static const char* const* z[];
};

const char* const Foo::a[] = {"a1", "a2", "a3"};
const char* const Foo::b[]= {"b1", "b2", "b3", "b4"};
const char* const* Foo::z[] = {a, b};

答案 2 :(得分:0)

这可以通过以下方式实现:

class clsMainWin{
    static const char* const mcpszXMLattrRoot[5];
    static const char* const mcpszXMLattrA[4];
    static const char* const *allOptions[2];

    // And other things....

};

const char* const clsMainWin::mcpszXMLattrRoot[] = {"bottom","left","right","top",NULL};
const char* const clsMainWin::mcpszXMLattrA[] = {"x","y","z",NULL};
const char*const * clsMainWin::allOptions[2] = {mcpszXMLattrRoot, mcpszXMLattrA};