我正在编写一个小人计算机模拟,我想重载索引运算符 []
。我创建了一个名为 LMC 的类并完成了以下操作:
#include <iostream>
using namespace std;
class LMC
{
public:
LMC();
void display();
int& operator[](int index);
~LMC();
private:
int **array;
};
LMC::LMC()
{
array = new int*[100];
for(int i = 0; i < 100; i++)
{
array[i] = new int[3];
}
return array;
}
void LMC::display()
{
for(int i = 0; i < 100;i++)
{
for(int j = 0; j <3;j++)
{
array[i][j] = 0;
array[i][2] = i;
cout << array[i][j]<<" ";
}
cout << endl;
}
}
int& LMC::operator[](int index)
{
return array[index][2];
}
LMC::~LMC()
{
for(int i =0; i < 100 ; i++)
{
delete [] array[i];
}
delete [] array;
array = NULL;
}
int main()
{
LMC littleman;
while(true)
{
int mailbox;
int function;
cout << "What is Mailbox number?" << endl;
cin >> Mailbox;
cout << "What is the function you want to use?" <<endl;
cin >> finction;
//the function is numbers eg 444 and 698;
littleman.display();
littleman[Mailbox] = function;
}
return 0;
}
我可以毫无错误地运行程序。当我这样说时mailbox = 0
,function = 123
这没问题。
显示如下:
0 0 0
1 0 0
2 0 0
3 0 0
//continuing to 99
这个显示是错误的。必须显示以下内容:
0 0 123
1 0 0
2 0 0
//continuing to 99
我是否有逻辑错误,或者我是否覆盖了数组以显示原始内容,我该如何解决?