【问题标题】:C++ - dereferencing pointers that are elements of an array?C++ - 取消引用作为数组元素的指针?
【发布时间】:2012-02-27 00:00:53
【问题描述】:

我有一个 Deck 类的对象,它包含一个动态分配的指针数组,指向另一个类 PlayingCard 的对象。我正在尝试重载

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 对象所持有的实际数据,而不仅仅是内存地址?

【问题讨论】:

  • 问题可能出在 getPlayingCards...
  • 您是否考虑过使用像 std::vector 或 std::set 这样的可迭代容器。至少这样你就可以有一个 getter 到集合的开始迭代器并迭代——至少这样你甚至不必担心指针(当然,这对PlayingCard 的复制构造函数)...更好的是,您还可以使用 Visitor 设计模式来遍历 PlayingCard 对象的集合,将遍历逻辑保留在 Deck 对象中...

标签: c++ arrays class pointers dereference


【解决方案1】:
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&lt;&lt; 方法为此重载,因此您需要*(pCards[i]),但您还必须确保对PlayingCard 类进行相应的重载。即带有签名的朋友功能:

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

糟糕,请阅读您的 cmets:

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

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

【讨论】:

  • 这是一个很好的问题,我不确定。我有 ostream& operator
【解决方案2】:

*pCards[i](*pCards[i])*(pCards[i]) 都在解除对对象的引用。您的程序的另一部分还有其他问题,可能是在 Deck 的实现中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2017-05-10
    • 2017-02-05
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多