C ++ - 解除引用作为数组元素的指针?

时间:2012-02-04 20:50:32

标签: c++ arrays class pointers dereference

我有一个Deck类的对象,它包含一个动态分配的指针数组,指向另一个类的对象,即PlayingCard。我试图重载<<运算符(作为类Deck的朋友)迭代地输出Deck对象中每张卡的详细信息。目前,重载定义如下所示:

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

当试图构造Deck对象并输出其卡片细节时,它会输出一个内存地址列表而不是实际数据,所以我想我需要取消引用pCards [i]。但是,当我尝试这样做时,输出是垃圾,我最终在调试器中达到访问冲突。我已经尝试了以下所有组合,但都导致编译时或运行时问题:

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

这是解除引用数组内指针的错误语法,还是有更深层次的东西我不在这里理解?如何重写此代码,以便程序输出这些PlayingCard对象所持有的实际数据,而不仅仅是内存地址?

2 个答案:

答案 0 :(得分:1)

*pCards[i](*pCards[i])*(pCards[i])都取消引用这些对象。你的程序的另一部分还有其他问题,可能是Deck的实现。

答案 1 :(得分: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.

您确定该方法对于您在上面显示代码的函数是否可见?