Home > Net >  C Parenthesis Operator Overloading Error
C Parenthesis Operator Overloading Error

Time:11-29

I am getting an unexpected error trying to implement ()-overloading according to the following get_chessman() method in a chessboard class: "expression preceding parentheses of apparent call must have pointer to function type". Am I overloading in the wrong way?

Minimal example code:

In chessboard header:

class Chessboard
{
private:
  Chessman** board;
  int size;
  bool turn; // 1 for white, 0 for black
public:
  Chessboard(int size = 8);
  ~Chessboard();
  bool is_whites_turn() const;
  bool is_game_over() const;
  int get_size() const { return size; }
  Chessman* operator() (int row, int col) const; // <------ overloading
  Chessman* get_chessman(int row, int col) const; // reference method
}

Implementation:

Chessman* Chessboard::operator()(int row, int col) const
{
  return &board[row][col];
}

Chessman* Chessboard::get_chessman(int row, int col) const
{
  return &board[row][col];
}

Result:

int main() {
  cout << "hello Chess" << endl;
  //Chessboard cb();
  Chessboard* cb = new Chessboard();
  cb->show();
  Chessman* cm = cb->get_chessman(7,4);
  cout << cm->get_symbol() << endl;
  Chessman* cm1 = cb(7, 4); // ERROR: expression preceding parentheses of apparent call must have (point-to-) function
  cout << cm1->get_symbol() << endl;
  return 0;
}

CodePudding user response:

Just like you dereference cb in cb->get_chessman(7,4), you must dereference it in the line in question, like (*cb)(7, 4).

Side note: the way you code is reminiscent of Java where everything is a pointer. You should probably make use of simple variables, references, and standard containers (among other things) when coding in C . Example:

class Chessboard
{
private:
  std::vector<std::vector<Chessman>> board;
  int size;
  bool turn; // 1 for white, 0 for black
public:
  Chessboard(int size = 8);
  ~Chessboard();
  bool is_whites_turn() const;
  bool is_game_over() const;
  int get_size() const { return size; }
  Chessman const& operator() (int row, int col) const; // <------ overloading
  Chessman const& get_chessman(int row, int col) const; // reference method
  void show();
};

Chessman const& Chessboard::operator()(int row, int col) const
{
  return board[row][col];
}

Chessman const& Chessboard::get_chessman(int row, int col) const
{
  return board[row][col];
}

int main() {
  std::cout << "hello Chess" << std::endl;
  Chessboard cb;
  cb.show();
  auto cm = cb.get_chessman(7,4);
  std::cout << cm.get_symbol() << std::endl;
  auto cm1 = cb(7, 4);
  std::cout << cm1.get_symbol() << std::endl;
}
  • Related