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

编写俄罗斯方块模拟程序时遇到Pointer-Object等编译错误求助

俄罗斯方块程序编译错误排查与修复

错误1:expression must have pointer-to-object type but it has type "int" / subscript requires array or pointer type

  • 出现位置:第16、39、51、62行
  • 原因:类中body被声明为int类型,但代码里直接把它当作二维数组(body[i][j])使用,C++不允许对普通int变量用下标运算符。
  • 解决方法:把body改成动态二维结构,推荐用vector<vector<int>>,无需手动管理内存,还能灵活适配自定义行列数。

错误2:'void' illegal with all types

  • 出现位置:第46行
  • 原因:一是代码里PlayerChoice == "Defualt"拼写错误(应为"Default");二是body类型错误导致body[i][j]调用非法,触发关联编译错误;另外bodyMeasure里的递归调用没加return,导致函数执行流混乱,也可能引发此类错误。
  • 解决方法:修正拼写错误,同时修复body的类型问题;把递归调用换成循环,避免栈溢出风险。

额外逻辑问题优化

  • bodyMeasure里的递归会导致重复输入行列时栈溢出,用循环替代递归更安全。
  • DisplayBody原本只输出值为0的位置,补充了非0情况的显示逻辑,方便后续方块渲染。

修正后的完整代码

#include<iostream>
#include<string>
#include<vector>
#include"Front.h"
using namespace std;

class field: public Front
{
public:
    int row, col;
    vector<vector<int>> body; // 替换为二维vector

    void bodyMeasure()
    {
        if (PlayerChoice == "Default")
        {
            row = 11;
            col = 11;
            body.assign(row, vector<int>(col, 0)); // 初始化11x11的空棋盘
        }
        else if (PlayerChoice == "Select Difficulty")
        {
            // 循环输入直到符合要求,替代递归
            while (true)
            {
                cout << "Enter the row of the Puzzle box: ";
                cin >> row;
                if (row >= 11)
                    break;
                cout << "Your Entry should be above or equal to 11!\n";
            }

            while (true)
            {
                cout << "Enter the column of the Puzzle box: ";
                cin >> col;
                if (col >= 11)
                    break;
                cout << "Your Entry should be above or equal to 11!\n";
            }

            body.assign(row, vector<int>(col, 0)); // 初始化自定义尺寸的棋盘
        }
    }

    void DisplayBody()
    {
        if(PlayerChoice == "Default") // 修正拼写错误
        {
            for (int i = 0; i < 11; i++)
            {
                cout << "\n";
                for(int j=0; j<11; j++)
                {
                    cout << (body[i][j] == 0 ? '-' : '#'); // 空位置显示'-',方块显示'#'
                }
            }
        }
        else if (PlayerChoice == "Select Difficulty") // 改用else if减少冗余判断
        {
            for (int i = 0; i < row; i++)
            {
                cout << "\n";
                for(int j=0; j<col; j++)
                {
                    cout << (body[i][j] == 0 ? '-' : '#');
                }
            }
        }
    }
};

内容的提问来源于stack exchange,提问作者Reza Arsenal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:41:19