C++ 将"this"指针用作普通指针

C++ Using the "this" pointer as a normal pointer

本文关键字:指针 this C++      更新时间:2023-10-16

我目前正在尝试使用"this"指针传递一个指针到一个函数:

void GameObject::process_events()
{
    std::vector<ObjectEvent*>::iterator it;
    for (it = events.begin(); it != events.end(); it++)
        (*it)->process(this);
}
Class ObjectEvent
{
private:
    bool* trigger;
    void (*response)(GameObject*);
public:
    process(GameObject* obj)
    {
        if (*trigger)
            response(obj);
    }
};

但是我得到一个错误:

No matching function call to 'ObjectEvent::process(GameObject* const)'

有什么问题吗?

根据您的错误消息判断,process_events()似乎实际上是一个const函数。

void GameObject::process_events() const
{
    process(this);
}

如果是,则this是const指针,process()必须接受const GameObject *。否则process()可能会修改传递给它的点,这违反了process_events不修改this的承诺。

void process(const GameObject* obj);

或者,从process_events()中删除const修饰符。

如果您从this中返回this的成员函数是const,那么它将是一个const指针。如果成员函数没有声明为const,指针也不会声明为

void GameObject::process_events()
{
    // ...
    process(this); // 'this' is NOT a const pointer
}
void GameObject::process_events() const
{
    // ...
    process(this); // 'this' IS a const pointer
}