默认参数:在非静态成员函数之外无效使用'this'
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);
}
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);
}
通过这样做,可以避免实现函数的主要逻辑的代码的重复。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 无法访问嵌套类.类的使用无效
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- C++错误:"error: int aaa::bbb is protected within this context"
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- FFMPEG配置文件级别id大小无效
- 错误:从"int"到枚举c++的转换无效
- 如何修复此错误:className::className的无效使用
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 'this'问题不大(在非成员函数中无效使用'this')
- 默认参数:在非静态成员函数之外无效使用'this'
- CC_SYNTHESIZE(int, beadColor, _BeadColor);在非静态成员函数之外无效使用'this'
- MinGW 4.7.0 到 4.7.2 错误:使用混合虚拟和非虚拟多重继承时成员函数中的"this"指针无效
- C++ 在非成员函数中无效使用 'this'
- 在非成员函数中无效使用 'this'