2011-12-14 83 views
1

我遇到了一個基本的數組問題,我似乎無法得到我的頭。傳遞數組到對象方法

我有一個類「StaticDisplayLayer」和構造函數有兩個參數 - 一個int和指針的3個無符號整型短的數組:

//constructor definition: 
StaticDisplayLayer(int type, unsigned short *displayColor[3]); 

//constructor code: 
StaticDisplayLayer::StaticDisplayLayer(int type, unsigned short *dColor[3]) : DisplayLayer(type) 
{ 
    displayColor = dColor; 
} 

我試圖創建一個類的實例使用以下:

unsigned short layerColor[3] = {(unsigned short)255,(unsigned short)255,(unsigned short)255}; 
StaticDisplayLayer myLayer(1, &layerColor); 

我的理解是,& layerColor是一個指針數組layerColor但編譯器是給我下面的錯誤:

no matching function for call to `StaticDisplayLayer::StaticDisplayLayer(int, short unsigned int (*)[3])' 
Candidates are: 
    StaticDisplayLayer::StaticDisplayLayer(const StaticDisplayLayer&) 
    StaticDisplayLayer::StaticDisplayLayer(GLenum, short unsigned int**) 

我知道第二個候選人是我正在嘗試使用的人,但顯然我不明白指向數組的指針的概念。如果有人能夠闡明如何調用構造函數和/或解釋這個的任何資源,我會很感激它 - 到目前爲止,我在網上的搜索並沒有真正發揮很大的作用。

+0

你有沒有考慮過爲此使用`std :: vector`?你可以用它來解決所有那些複雜的語法。 – Naveen 2011-12-14 17:47:47

+0

是的,我正要用矢量來重寫它,但不想只是讓我不明白自己做錯了什麼。 – TheOx 2011-12-14 17:59:45

回答

5

unsigned short *dColor[3]不是指向數組的指針,它是指向數組的指針。 [3]被忽略並被另一個指針替換,因爲它是一個函數參數。換句話說,它衰變。要製作一個指向數組的指針,請使用unsigned short (*dColor)[3],這是一個指向數組大小爲3到unsigned short的指針。

一種在C++中甚至更好的想法是使用一個參照的數組:

unsigned short (&dColor)[3] 

而只是通過layerColor

+0

對於建議使用參考的+1。 – 2011-12-14 17:51:29

1

&layerColor有型號pointer to array of 3 unsigned shorts。另一方面,您的構造函數預計unsigned short *[3]array of three pointers to unsigned short。事實上,作爲函數參數類型,它是一個pointer to pointer to unsigned short - 維度被完全忽略。我想你的意思是你的構造方法來只是一個指向unsigned short並通過layerColor

StaticDisplayLayer(int type, unsigned short *displayColor); 

unsigned short layerColor[3] = {255,255,255}; 
StaticDisplayLayer myLayer(1, layerColor); 

注意,在這種情況下,調用者的責任傳遞中有至少3個元素的數組。另外,您可以使功能拍攝的正是3 ushorts陣列通過手段

StaticDisplayLayer(int type, unsigned short (&displayColor)[3]); 

但在這種情況下,您將無法通過動態分配數組。

我不能不注意到,你沒有在C++的一些基本知識,所以我建議你閱讀good C++ book

1

無符號短displayColor [3]是說一個無符號的短指針或基本無符號短*的陣列。

unsigned short layerColor [3]是一個無符號短數組,而不是一個無符號短指針數組。

我會爲顏色創建一個結構或類,然後將指針或引用傳遞給一個。