[英]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.