[英]default argument : invalid use of 'this' outside of a non-static member function
I try to have a default parameter in my functions but the compiler says there is an error : 我尝试在函数中使用默认参数,但编译器说有错误:
invalid use of 'this' outside of a non-static member function
How can I fix this ? 我怎样才能解决这个问题 ?
Edit : @RSahu, here is the two overloaded functions, can you explain me how I can manage the problem because apparently I didn't understand how to fix it. 编辑: @RSahu,这是两个重载函数,您能否解释一下我如何处理该问题,因为显然我不知道如何解决该问题。
Game.hpp : 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 : 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;
}
Thanks for you help ! 谢谢您的帮助!
this
can be used only inside the body of a non-static member function. this
只能在非静态成员函数的主体内部使用。 Hence, your use of this->board
as the default value of the input is not correct. 因此,您使用this->board
作为输入的默认值是不正确的。
I suggest creating an overload to get around the problem. 我建议创建一个重载来解决该问题。
class Game {
private :
int** board;
vector<pair <int, int> > listPiecesPosition(int** board);
vector<pair <int, int> > listPiecesPosition()
{
return listPiecesPosition(this->board);
}
PS this
can appear outside the body of a member function in limited contexts. PS this
可以在有限的上下文中出现在成员函数的主体之外。 This is not one of those situations. 这不是其中一种情况。
Update, in response to OP's comment 更新,以回应OP的评论
Change 更改
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;
}
to 至
vector<pair <int, int> > Game::listPiecesPosition() {
return listPiecesPosition(this->board);
}
By doing this, you avoid duplication of code that implements the main logic of the functions. 通过这样做,可以避免实现功能主要逻辑的代码重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.