默认参数:在非静态成员函数之外无效使用'this'

default argument : invalid use of 'this' outside of a non-static member function

本文关键字:无效 this 参数 函数 静态成员 默认      更新时间:2023-10-16

我试图在函数中有一个默认参数,但编译器说有一个错误:

invalid use of 'this' outside of a non-static member function

我该怎么解决这个问题?

编辑:@RSahu,这是两个过载的函数,你能解释我如何处理这个问题吗?因为显然我不知道如何解决它。

Game.hpp:

class Game {
 private :
  int** board;
  vector<pair <int, int> > listPiecesPosition();
  vector<pair <int, int> > listPiecesPosition(int** board);
  // What doesn't work
  vector<pair <int, int> > listPiecesPosition(int** board = this->board); 

Game.cpp:

//Here I need to write more or less two times the same function, how can I do it only once ?
   vector<pair <int, int> > Game::listPiecesPosition() {
vector<pair <int, int> > listPiecesPosition;
for (int i=0; i < getSize(); i++)
  for (int j=0; j < getSize(); j++)
    if (getBoard()[i][j] == nextPlayer.getColor()) // Here I don't use the parameter
      listPiecesPosition.push_back(make_pair(i,j));
return listPiecesPosition;
  }
  vector<pair <int, int> > Game::listPiecesPosition(int** board) {
    vector<pair <int, int> > listPiecesPosition;
    for (int i=0; i < getSize(); i++)
      for (int j=0; j < getSize(); j++)
        if (board[i][j] == nextPlayer.getColor()) // Here I use the parameter
          listPiecesPosition.push_back(make_pair(i,j));
    return listPiecesPosition;
  }

谢谢你的帮助!

this只能在非静态成员函数的内部使用。因此,将this->board用作输入的默认值是不正确的。

我建议制造一个超负荷来解决这个问题。

class Game {
 private :
  int** board;
  vector<pair <int, int> > listPiecesPosition(int** board);
  vector<pair <int, int> > listPiecesPosition()
  {
     return listPiecesPosition(this->board);
  }

PSthis可以在有限的上下文中出现在成员函数的主体之外。这不是那种情况。

更新,以回应OP的意见

更改

vector<pair <int, int> > Game::listPiecesPosition() {
   vector<pair <int, int> > listPiecesPosition;
   for (int i=0; i < getSize(); i++)
      for (int j=0; j < getSize(); j++)
         if (getBoard()[i][j] == nextPlayer.getColor()) // Here I don't use the parameter
            listPiecesPosition.push_back(make_pair(i,j));
   return listPiecesPosition;
}

vector<pair <int, int> > Game::listPiecesPosition() {
   return listPiecesPosition(this->board);
}

通过这样做,可以避免实现函数的主要逻辑的代码的重复。