You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ Chessboard类重载()运算符报错,请求排查错误原因

解决()运算符重载报错:expression preceding parentheses of apparent call must have pointer to function type

你在Chessboard类中实现()运算符重载时遇到的报错,并非重载方式有误,问题出在调用语法上。

头文件代码

class Chessboard
{
private:
  Chessman** board;
  int size;
  bool turn; // 1代表白方,0代表黑方
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; // 运算符重载
  Chessman* get_chessman(int row, int col) const; // 参考方法
};

实现代码

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];
}

调用代码及报错

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); // 错误:expression preceding parentheses of apparent call must have (point-to-) function
  cout << cm1->get_symbol() << endl;
  return 0;
}

错误原因

cb是Chessboard*类型的指针,而你重载的operator()是成员函数,只能作用于Chessboard对象,不能直接作用于指针。直接写cb(7,4)会被编译器解析为“调用一个名为cb的函数并传入参数7和4”,但cb是指针而非函数,因此触发报错。

解决方案

有两种正确的调用方式:

  1. 先对指针解引用得到对象,再调用重载的运算符:
Chessman* cm1 = (*cb)(7, 4);
  1. 直接以成员函数的形式调用operator():
Chessman* cm1 = cb->operator()(7, 4);

另外,若无需动态分配对象,也可直接声明栈对象,这样就能直接用cb(7,4)调用:

Chessboard cb; // 注意不要写成Chessboard cb(); 这会被编译器解析为函数声明
Chessman* cm1 = cb(7,4);

内容的提问来源于stack exchange,提问作者marie_antoinette

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:50:39