【问题标题】:C++ Passing pointer to current object to a functionC ++将指向当前对象的指针传递给函数
【发布时间】: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
}

我做错了什么?如何获得指向当前对象的指针?

thisChess* const

*this 给了我一个Chess&amp;,当我尝试这样做时:

list&lt;Move *&gt; moves = p-&gt;getMoves(*this);

我收到no matching function for call to ‘ChessPiece::getMoves(Chess&amp;)’

编辑

每个人都在告诉我这样做:

list&lt;Move *&gt; moves = p-&gt;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-&gt;getMoves(this) 之前,您有#include-d 带有ChessPiece 的标头吗?
  • @BenVoigt 是的,当然
  • 好吧,如果所有代码都放在一个文件中,带有this(不是*this)的版本编译得很好。见ideone.com/VpNQEY所以你的头文件有问题。
  • @BenVoigt:但忘记了 piece.h 中的#include chess.h!就是这样!谢谢:)
  • 很高兴你解决了。

标签: c++ pointers this


【解决方案1】:

getMoves(Chess *game) = 0;

getMoves 以 Chess 类的指针为参数。

列出移动 = p->getMoves(*this);

你在这里传递 *this,但 this 本身是一个指针。

so >list move = p->getMoves(this);

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 2017-08-09
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多