我正在写一个小人计算机模拟,我想重载索引运算符[]
。我创建了一个名为LMC的类,并完成了以下操作:运算符C++中的重载和数组处理
#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
我有一个逻辑上的错误还是我重写阵列显示原始和如何解决呢?
请为自己节省麻烦,并为您的内部数组使用'std :: vector>'而不是'int **'。 –
'0 0 0'这是'LMC :: display()'的输出吗? – Andrey
@Andrey是的,这是输出。 –