2012-02-04 30 views
3

我有一個Deck類的對象,其中包含一個指向另一個類的對象的指針的動態分配數組,遊戲卡。我試圖超載< <運算符(作爲Deck類的朋友),以迭代方式輸出Deck對象中每張牌的細節。目前超負荷的定義是這樣的:C++ - 取消引用是數組元素的指針?

ostream& operator<< (ostream& out, const Deck& d) 
{ 
    PlayingCard** pCards = d.getPlayingCards(); 
    for(int i = 0; i < d.getTotalCards(); ++i) 
    { 
     out << pCards[i] << endl; 
     // the << operator is also overloaded in the PlayingCard class to take PlayingCard objects as arguments. 
     // the overload in the PlayingCard class definitely works. 
    } 

    return out; 
} 

當試圖構建一個甲板對象,並輸出其信用卡細節,它輸出的內存地址,而不是實際的數據列表,所以我想我需要取消引用pCards [一世]。但是,當我嘗試這樣做時,輸出是垃圾,最終在調試器中遇到訪問衝突。我已經嘗試了所有的以下連擊的,但所有導致無論是在編譯時或運行時的問題:

*pCards[i], pCards[i]*, (*pCards[i]), *(pCards[i]) 

是解引用指針數組內的是這只是不正確的語法,還是有更深層次的東西我在這裏不理解?我該如何重寫這段代碼,以便程序輸出由這些PlayingCard對象保存的實際數據,而不僅僅是內存地址?

+0

問題可能是在getPlayingCards ... – 2012-02-04 20:52:46

+0

你有沒有使用迭代容器比如std :: vector的或std ::設置,而不是考慮。至少你可以通過這種方式獲得集合的開始迭代器的getter,並且只需迭代 - 至少這樣你就不用擔心指針了(當然,這對於可用性有一定的假設更好的是,您還可以使用Visitor設計模式遍歷PlayingCard對象的集合,在Deck對象中保留遍歷邏輯... – hatboyzero 2012-02-04 21:01:26

回答

1

*pCards[i](*pCards[i])*(pCards[i])都取消引用的對象。在程序的另一部分還有其他問題,可能是在執行Deck

0
ostream& operator<< (ostream& out, const Deck& d) 
{ 
    PlayingCard** pCards = d.getPlayingCards(); 
    for(int i = 0; i < d.getTotalCards(); ++i) 
     out << (*(pCards[i])) << endl; 
    return out; 
} 

你傳入pCards[i]這是一個指向PlayingCard(= PlayingCard *)。不會有operator<<方法超載,所以你需要*(pCards[i]),但你必須確保你有類PlayingCard相稱的超載。即與簽名友元函數:

ostream& operator<< (ostream& out, const PlayingCard& d); 

哎呀,剛剛看了你的評論:

 // the << operator is also overloaded in the PlayingCard class to take PlayingCard objects as arguments. 
     // the overload in the PlayingCard class definitely works. 

你確定方法是,你已經證明代碼上面的功能可見?

+0

這是一個非常好的問題,並且我不確定。作爲PlayCard類的朋友功能,我有ostream&operator <<(ostream&out,const PlayingCard&pc)。然後在Deck的頭文件中對PlayingCard進行前向聲明,最後將兩個類的頭文件包含在Deck的源文件中。 – 2012-02-04 21:04:37