저는 Littleman 컴퓨터 시뮬레이션을 작성 중이며 인덱싱 연산자 []
에 과부하를 걸고 싶습니다. 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
내가 논리적 오류가 있습니까 또는 내가 원본을 표시하고 어떻게 고칠 수 배열을 무시하고? LMC::display()
에서
내부 배열의 문제를 해결하고'int **'대신'std :: vector>'을 사용하십시오. –
'0 0 0' 그것은'LMC :: display()'의 출력입니까? – Andrey
@Andrey 예, 출력물입니다. –