Grid Matrix: operator() Over a Single Heap Buffer
hardQuestion 711Write a class Grid that stores a rows x cols matrix of ints in ONE dynamically allocated block (not an array of arrays) and exposes its elements through operator(). Do NOT write a main function; a hidden test provides one.
Required members:
- Grid(int rows, int cols) - allocates rows * cols ints with new[], every element 0.
- ~Grid() - releases the block.
- int& operator()(int r, int c) - returns a REFERENCE.
- int operator()(int r, int c) const - the read-only version, used through a const Grid&.
- int rows() const and int cols() const.
Element (r, c) lives at index r * cols + c of the block (row-major order).
Free the memory you allocate - this question checks for memory leaks.
The hidden test reads rows and cols, prints the dimensions and the starting value of (0, 0), reads rows * cols numbers into the grid, prints it one row per line with single spaces, prints the sum of every element, then multiplies (0, 0) by 10 and prints it. It hands the grid to a helper taking a const Grid&, so BOTH operator() overloads are required.
For the input: 2 3 1 2 3 4 5 6
your class must produce exactly the output shown in Expected Output.
Expected output
2x3 start 0 1 2 3 4 5 6 sum=21 scaled=10
= newline. The output ends with a newline, so print one after the last line.
Your output
Run your code to see the output here...