[英]invalid use of 'this' outside of a non-static member function error?
[英]default argument : invalid use of 'this' outside of a non-static member function
我尝试在函数中使用默认参数,但编译器说有错误:
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);
}
PS this
可以在有限的上下文中出现在成员函数的主体之外。 这不是其中一种情况。
更新,以回应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);
}
通过这样做,可以避免实现功能主要逻辑的代码重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.