Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating [][] operator for class in c++

I am making a Pentago game for someone, and I wanted to write a good code, so I decided to use operator overloading.

We have 2 classes; first one is Block class (which represents every single block of the board) and the second one is Set class (which represents a 3*3 table of blocks). Now I want to use Set as a 2d array so I can use set[foo][foo]. Can you help me to make an operator like this?

like image 570
Roozbeh Avatar asked Feb 10 '23 17:02

Roozbeh


1 Answers

A very simple solution is

struct MyClass {
    int x[3][3];
    int* operator[](int row) { return &(x[row][0]); }
};

i.e. returning an element* from operator[].

This allows using

myinstance[row][col]
like image 71
6502 Avatar answered Feb 13 '23 02:02

6502