【发布时间】:2014-01-21 05:52:28
【问题描述】:
这是标题问题,我忘了包含标题...
我们应该使用getMoves(this)
我需要将一个指向当前对象的指针发送给一个函数,但无法找到如何去做...:/
chess_piece.h
class ChessPiece
{
public:
virtual std::list<Move *> getMoves(Chess *game) = 0;
};
chess.cpp
list<Move *> Chess::getMoves()
{
ChessPiece *p;
...
list<Move *> moves = p->getMoves(*this);
// can't manage to get a pointer to the current object here
}
我做错了什么?如何获得指向当前对象的指针?
this 是Chess* const
*this 给了我一个Chess&,当我尝试这样做时:
list<Move *> moves = p->getMoves(*this);
我收到no matching function for call to ‘ChessPiece::getMoves(Chess&)’
编辑
每个人都在告诉我这样做:
list<Move *> moves = p->getMoves(this);
但我已经尝试过了,我得到了:
no matching function for call to ‘ChessPiece::getMoves(Chess* const)’
EDIT2
这是我对 Chess::getMoves() 的声明:
chess.h
class Chess : public Game
{
public:
std::list<Move *> getMoves();
};
【问题讨论】:
-
this成为Chess* const很好,也很符合预期。在尝试调用p->getMoves(this)之前,您有#include-d 带有ChessPiece的标头吗? -
@BenVoigt 是的,当然
-
好吧,如果所有代码都放在一个文件中,带有
this(不是*this)的版本编译得很好。见ideone.com/VpNQEY所以你的头文件有问题。 -
@BenVoigt:但忘记了 piece.h 中的
#includechess.h!就是这样!谢谢:) -
很高兴你解决了。