【问题标题】:How to get a class to cout as one of its array properties如何让一个类作为它的数组属性之一
【发布时间】:2018-05-23 01:59:42
【问题描述】:

我是 C++ 新手(我常用的语言是 Python)。

我从here 发现了如何打印数组。我从here 发现了如何将一个类对象作为cout 的属性之一。我从here 发现cout 仅在它可以作为friend 访问类的属性时才有效。

但是,当我结合答案时,它似乎不起作用。 这是我得到的:

#include <iostream>
using namespace std;

class TicTacToeGame {
    int board[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};

    friend std::ostream &operator<<(std::ostream &os, TicTacToeGame const &m);
};

std::ostream &operator<<(std::ostream &os, TicTacToeGame const &m) {
    for (int i = 0; i++; i < 9) {
        os << m.board[i];
    }
    return os;
}

int main()
{
    TicTacToeGame game;
    cout << game;
    return 0;
}

屏幕上没有任何内容。

我希望看到类似于{0, 0, 0, 0, 0, 0, 0, 0, 0} 的内容,但只要我能看到数组,就不需要花哨的格式。

我怎样才能做到这一点?

【问题讨论】:

  • 你应该在cout &lt;&lt; game之后输出一个换行符或endl
  • @M.M 我为什么要这样做?
  • 标准输出默认是行缓冲的,因此任何部分行可能永远不会出现在您的屏幕上;这取决于操作系统和调用环境
  • 看来我的回答已经(意外地)做到了。谢谢你让我知道我应该保持这种状态。
  • 您需要至少再启用一个警告:我的代码编译生成:“警告:增量表达式无效 [-Wunused-value]”

标签: c++ class cout


【解决方案1】:

修复 for 循环。

for (int i = 0; i++; i < 9) {

应该是

for (int i = 0; i < 9; i++) {

【讨论】:

    【解决方案2】:

    感谢 @immibis 再次提醒我如何执行 for 循环。 (我已经很久没有这样做了……)

    这是我决定暂时使用的更高级的操作员函数版本,这样它就可以像井字棋一样打印出来了。

    std::ostream &operator<<(std::ostream &os, TicTacToeGame const &m) {
        for (int i = 0; i < 9; i++) {
            os << m.board[i];
            if (i%3!=2) {
                os << " ";
            }
            if (((i+1) % 3) == 0) {
                os << "\n";
            }
        }
        return os;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2022-01-10
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多