首页 > 解决方案 > 解决错误:operator[] 不匹配

问题描述

以下代码给出了此错误:

错误:'operator[]' 不匹配(操作数类型为 'S' 和 'int')|"

在第 38、40、52、53、54、54、67、67 行(是的,在 54 和 67 出现两次相同的错误)。

#include <iostream>

using namespace std;

const int m=3;

class S
{
public:

    int col;
    char ch;


    int getcolumn()
    {
        return col;
    }

    int getrow()
    {
        int t=ch; t-=65;
        return t;
    }
};


void input(S *mat)
{
    int i,j;

    for(i=0;i<m;i++)
    {
        cout<<endl<<"ROW "<<i+1;
        for(j=0;j<m;j++)
        {
            cout<<endl<<"COLUMN "<<j+1<<endl;
            cout<<"enter the number";
            cin>>mat[i][j].col;
            cout<<"enter the letter";
            cin>>mat[i][j].ch;
        }
    }
}

void logic(S *orig,S *repl)
{
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<m;j++)
        {
            int coll=orig[i][j].getcolumn();
            int row=orig[i][j].getrow();
            repl[row][coll]=orig[i][j];
        }
    }
}


void output(S *repl)
{
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<m;j++)
        {
            cout<<repl[i][j].col<<repl[i][j].ch<<"   ";
        }
        cout<<endl;
    }
}

int main()
{
    int i,j;

    S orig[10][10],repl[10][10];

    input(&orig[0][0]);
    logic(&orig[0][0],&repl[0][0]);
    output(&repl[0][0]);

    return 0;
}

如何解决错误?我正在使用带有 GCC 编译器的 code::blocks 17.12。我对c ++很陌生,所以请以更详细的方式解释一下。

标签: c++

解决方案


问题是一旦数组转换为指针,就只能对其进行一维指针运算。您的函数采用 类型的参数S *,即指向 的指针S

让我们来吧output(S *repl)repl是一个指向S. 这意味着 that repl[i]is (a reference to) an S. 现在,你[j]再次申请,但S没有任何这样的运算符,所以它出错了。

您需要做的是手动进行 2D 索引,可能是这样的:

size_t idx2d(size_t i, size_t j, size_t iCount)
{
    return j * iCount + i;
}

void output(S *repl, size_t iCount)
{
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<m;j++)
        {
            cout<<repl[idx2d(i, j, iCount)].col<<repl[idx2d(i, j, iCount)].ch<<"   ";
        }
        cout<<endl;
    }
}

// In main:

output(&repl[0][0], 10);

推荐阅读