2016-04-01 120 views
2

我需要指針聲明的幫助,我有幾個指針數組的類例如。C++指針聲明訪問指針數組

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正確的聲明。

+0

你不能真的做臨時工t,因爲'mcpszXMLattrRoot'和'mcpszXMLattrA'是不同的類型,這意味着你不能將它們收集到同一個數組中。 'mcpszXMLattrRoot'的類型是'const char * const [5]',而'mcpszXMLattrA'的類型是'const char * const [4]'。數組中元素的數量是類型的一部分,而數組只能包含相同類型的元素。 –

+0

這是一個C++問題,而不是C問題。請刪除'c'標籤 – user3629249

回答

2

你可以存儲mcpszXMLattrRootmcpszXMLattrA(即const char * const *。指針

const char* const * allOptions[] = {mcpszXMLattrRoot, mcpszXMLattrA}; 
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具有附加*,因爲它是一個指針到炭的指針數組的數組。

因爲ab*之前需要const常量。如果沒有constantness這將是:

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

立即嘗試此操作:const char * const * clsMainWin :: mcppAttributes [] – SPlatten

+0

此答案不允許使用單個索引進行訪問。 – Peter

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