Background to the question:
I have been writing a small program to solve the daily Reddit challenge (details of the challenge are posted here for those interested).
While doing so, I appreciate my design is not the best, but i opted to write a class as an interface for carrying out different operation in a specific order of +1, +number, -1 and -number. Then in my main code I simple called operation.calculate(baseNumber) or operation.incrementOperation() to move to the next designated operation. However I hit an issue when trying to implement the class which I can't understand why it won't work. The code I was trying to implement was:
class DesignatedOperation
{
public:
DesignatedOperation() : operationId(0) {}
~DesignatedOperation() {}
void incrementOperation()
{
operationId += 1;
if (operationId > 3) { operationId = 0; }
}
int calculate(int number)
{
int op1 = operations[operationId, 0];
int op2 = operations[operationId, 1];
return (op1 + number * op2);
}
private:
int operationId;
int operations[4][2] = { 1, 0, 0, 1, -1, 0, 0, -1 };
};
However I am not able to compile this as I get the error for the lines accessing the operations array with the square brackets:
a value of type "int *" cannot be used to initialize an entity of type "int"
Now looking through examples for tutorials such as this, I can't figure out why this is not working. Now as a workaround I found I could using a single dimension array changing the code to the following:
class DesignatedOperation {
public:
DesignatedOperation() : operationId(0) {}
~DesignatedOperation() {}
void incrementOperation()
{
operationId += 2;
if (operationId > 6) { operationId = 0; }
}
int calculate(int number)
{
int op1 = operations[operationId];
int op2 = operations[operationId+1];
return (op1 + number * op2);
}
private:
int operationId;
int operations[8] = { 1, 0, 0, 1, -1, 0, 0, -1 };
};
Question at hand
I know this appears trivial but I was trying to google if this is a specific issue with using multidimensional arrays in classes like this but I wasn't much luck working exactly what is going here, beside me missing an obvious mistake.
Not sure if anyone else has encountered this or knows the underlying reason why my code can't access the array?
I can change the code on those to lines to allow it to compile by de-referencing the array as if it was a pointer but this doesn't make sense to me as I have not declared operations as a pointer to an array and it's within the scope of the class. Running this compiled code produces garbage output, as I would expect.
Any pointer in the right direction would be really appreciated, Thanks.
For reference I am using Microsoft Visual Studio Community 15 (Microsoft Visual C++ 2015).