This code is
really confusing.
The culprit here is that your [] operator is returning a
copy of the cell, and not the actual cell in the grid. So when you SetValue, you're actually setting the value in a copy... leaving gridBoard's copy unchanged.
You can fix this by having your [] operator return by reference.
But... again... your organization here is very strange. For starters, 'cell' is inappropriately named, since it's actually 4 different cells and not actually a single individual cell as the name implies. Futhermore, there's no real reason to have two classes like this. And there isn't even really a reason to use a vector here.
And your state-based approach to keep track of the current index is very, very weird and would allow for some very convoluted code.
This can all be greatly simplified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <vector>
using namespace std;
class grid
{
public:
grid()
{
values.resize(4,2.0f);
}
float& operator [] (int index)
{
return values[index];
}
private:
vector<float> values;
};
int main()
{
grid gridBoard;
gridBoard[3] = 4.0f;
cout << gridBoard[3] << endl;
system("pause");
return 0;
}
|
Or .... if you want explicit get/set functions instead of array-style access:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <vector>
using namespace std;
class grid
{
public:
grid()
{
values.resize(4,2.0f);
}
float getCell(int index)
{
return values[index];
}
void setCell(int index, float val)
{
values[index] = val;
}
private:
vector<float> values;
};
int main()
{
grid gridBoard;
gridBoard.setCell(3, 4.0f);
cout << gridBoard.getCell(3) << endl;
system("pause");
return 0;
}
|