You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用cout输出自定义game类数组元素时出现报错如何解决?

错误原因

  • 你的需求要求提示语中Input name of game x:里的x是games数组的下标位置,也就是当前循环的变量i,但你的代码错误写为了games[i],games[i]是你自定义的game类的实例对象。
  • C++标准库没有默认实现自定义game类的<<流输出运算符,编译器无法识别如何将game类对象输出到cout流,因此会在<<符号位置报语法错误。

修复方案

如果仅需要输出下标序号,直接将games[i]替换为循环变量i即可,修改后的代码行如下:

cout << "Input name of game " << i << ": ";

如果后续需要直接输出game类对象的完整信息,可以在game类中重载<<运算符,示例实现如下,将代码添加到game.h的类声明外部即可:

friend std::ostream& operator<<(std::ostream& os, const game& g) {
    os << "名称:" << g.name << ",类型:" << g.genre << ",难度:" << g.difficulty;
    return os;
}

额外优化建议

你的代码目前存在内存泄漏问题:循环内每次new出来的ptrObj对象赋值给数组后没有释放,且不需要额外堆分配对象,直接操作数组元素即可,优化后的循环参考代码:

for (int i = 0; i < numGames; i++)
{
    cout << "What is the name of the game?\n";
    cin >> name;
    cout << "What is the genre of " << name << "?\n";
    cin >> genre;

    cout << "Input name of game " << i << ": ";

    randomNumber = rand() % 10 + 1;
    // 直接操作数组内的对象,无需额外堆分配
    games[i].setName(name);
    games[i].setGenre(genre);
    games[i].setDifficulty(randomNumber);
}
// 程序结束前记得释放games数组的堆内存
delete[] games;

内容的提问来源于stack exchange,提问作者Conrad Speak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:06:04