简体   繁体   中英

How can i update a 2D array member of one class inside another class?

I have a class called Renderer that has an array of image objects called imageList and a 2D 80 by 80 array called canvas. Each image object has an array of shape objects called shapesList. Shapes can be a line, quadilateral, triangle or circle.

I want to update the 2D canvas array from the renderer class inside a function called draw which is in the the Line class.

I tried making a setter and getter for canvas to access it from inside the Line class but it does not seem to work. Maybe i can pass its reference? any help?

class Renderer {

private:
    char **canvas;
    Image **imageList;



//this is the constructor for Renderer
Renderer(){

//allocating mem for canvas
canvas = new char*[80];//height
for (int i = 0; i < 80; ++i) {
    canvas[i] = new char[80]; //width

}

Your current implementation looks alright, but usually if you're dealing directly with char 's, you may want to make canvas a single char* with:

private:
  char canvas[80*80];

This will also make sure that the memory is allocated on the stack instead of the heap (unless you need it to be dynamic in size).

Then you could just write a getter and setting as such:

char get(int row, int col) {
  return canvas[row * 80 + col];
}

char set(int row, int col, char val) {
  canvas[row * 80 + col] = val;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM