0

我知道你可以使用傳遞多維數組成一個函數:傳遞類之間的多維數組

void Class1::foo(Bar bars[][10]) 
{ 
    // Do stuff 
} 

和你可以指針在一個一維數組,通過使用返回到第一個構件:

Bar* Clas2::getBars() 
{ 
    return bars; //Where bars is a member of a class 
} 

然而,當 '酒吧' 是一個多維數組,我得到的錯誤:

Cannot convert Bar (*)[10] to Bar* in return

有人可以澄清爲什麼發生這種情況?

回答

1

你應該寫,因爲編譯器說

Bar (*)[10] Clas2::getBars() 
{ 
    return bars; //Where bars is a member of a class 
} 

你正確地說,「你可以在一個陣列..返回一個指向第一個成員。」您的二維數組的成員或更精確的元素是Bar [10]類型的一維數組。 指針到該元素將看起來Bar (*)[10]

哦,我很抱歉,確實應爲

Bar (* Clas2::getBars())[10] 
{ 
    return bars; //Where bars is a member of a class 
} 

或者你可以使用的typedef。例如

typedef Bar (*BarPtr)[10]; 
BarPtr Clas2::getBars() 
{ 
    return bars; //Where bars is a member of a class 
} 
+0

當我這樣做,我得到的錯誤:「不合格-ID之前 ')' 的道理,並指出getBars()不返回任何類型 – Xemerau

+0

@Xemerau我更新了我的帖子如果您使用了上面的帖子中的構造,那麼錯誤是什麼以及您使用了什麼構造? –

+0

錯誤來自您的解決方案在更新之前發佈,使用typedef修正了它。萬分感謝。 – Xemerau

0

你應該使用:

Bar (*Clas2::getBars())[10] 
{ 
    return bars; //Where bars is a member of a class 
} 

或更好看的方式:

typedef Bar (*Bar10x10ptr)[10]; 

Bar10x10ptr Clas2::getBars() 
{ 
    return bars; //Where bars is a member of a class 
} 
+0

如果我這樣做,我得到一個錯誤,指出'getBars'是一個聲明爲返回數組的函數,這看起來像我想要做的。 – Xemerau

+0

在GCC上它工作正常。 嘗試用'int'而不是'Bar'來測試它。 或者你可以試試這個: 'Bar(* a)[10]; decltype(a)Clas2 :: getBars() { return bar; //其中酒吧是一個類 }的成員' – HolyBlackCat