c++ - 解决错误: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 ++很陌生,所以请以更详细的方式解释一下。
解决方案
问题是一旦数组转换为指针,就只能对其进行一维指针运算。您的函数采用 类型的参数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);
推荐阅读
- lua - LUA 元表可以帮助检测 nilling 对象吗?
- tensorflow - TensorFlow:如何在不包括零的张量中找到分割的最小/最大坐标?
- java - 当我在 java 中执行更新查询时遇到一些问题
- java - 如何找到相对文本大小
- android - FirebaseOptions.getProjectId() 不能为空 Xamarin Android
- python - 以列表为输入对字符串进行切片
- php - jquery post请求已发送但未收到
- android - 我应该在我的 android 项目中使用哪个 compileSdkVersion?
- android - Android studio中的随机图片
- go - 如何写一个向量