c++ - 必须调用对非静态成员函数的引用

标签 c++ opengl-es openframeworks

我有一个 vector bars,它包含几个彩色框对象。每个框对象都有自己的绘制和更新函数。每个框从屏幕的一侧移动到另一侧。当它在屏幕外时,盒子应该被移除。我正在使用迭代器移动框并确定它们何时在屏幕之外。

我是 c++ 的新手,我在让代码工作时遇到了问题。从 vector 中删除对象的函数给我错误 Reference to non static member function must be called。我正在阅读有关静态和非静态成员的内容,但我仍然有点迷茫。

这是我的主要头文件和相关代码

class game : public ofxiPhoneApp {
    public:
    void setup();
    void update();
    void draw();
    void exit();

    vector <Colorbar> bars;
    bool checkBounds (Colorbar &b); 
};

在我的 game.mm 文件中,我创建了 vector 并对其进行迭代以设置彩色条对象的属性:

void game::setup(){
    bars.assign(5, Colorbar());
    for (int i = 0; i<bars.size(); i++) {
        ofColor color = colors.giveColor();
        bars[i].setup();
        bars[i].setColor(color.r,color.g,color.b);
        bars[i].setWidth(50);
        bars[i].setPos(ofGetScreenHeight()-(i*50), 0);
    }
}

在屏幕上移动横条的更新函数。

void game::update(){
    for(vector<Colorbar>::iterator b = bars.begin(); b != bars.end(); b++){
        (*b).update();
    }
    //this is the part that gives the error
    bars.erase((remove_if(bars.begin(), bars.end(), checkBounds),bars.end()));

}

下面是检查框是否越界的函数

bool game::checkBounds (Colorbar &b){

    if (b.pos.x > ofGetScreenHeight()+50) {
        // do stuff with bars vector here like adding a new object

        return true;
    } else {
        return false;
    }
}

我做了一些实验,并制作了 bool checkBounds (Colorbar &b); 非静态通过从头文件中删除它使代码工作。但问题是我还希望能够访问该函数中的 bars vector ,以便在删除旧对象时添加新对象。这将不再有效。

我该如何解决这个问题?

最佳答案

您需要一个采用ColourBar 的一元仿函数。成员函数有一个隐含的第一个参数 this。这意味着它不能这样调用:

Colorbar cb;
game::checkBounds(cb);

它需要绑定(bind)到它的类的一个实例,否则它将无法访问该实例的其他成员。因此,您需要将 checkBounds 成员函数绑定(bind)到 game 的实例。在您的情况下,this 看起来像是要绑定(bind)的正确实例:

#include <functional> // for std::bind

using std::placeholders; // for _1
...
remove_if(bars.begin(), bars.end(), std::bind(&game::checkBounds, this, _1)) ...

关于c++ - 必须调用对非静态成员函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18057130/

相关文章:

c++ - 如何将复杂的 C++ XCode 项目转换为 Cocoa 应用程序?

c++ - OpenCV:grabcut.cpp 错误

python - Python和Haskell有C/C++的 float 不确定性问题吗?

android - 为什么 OpenGL 纹理在 Eclipse 中使用调试器运行时呈现良好,但在单独运行应用程序时呈现白色?

android - 了解Android相机SurfaceTexture和MediaCodec Surface的使用

c++ - 什么时候需要无锁数据结构来跨线程读取/写入音频应用程序中的数据?

opencv - 如何计算openframeworks中ofColors之间的距离

c++ - 为什么 NULL 不能作为 std::thread 执行函数的 void* 参数的参数?

c++ - 在 C++ 中使用 put_time 获取毫秒精度的当前时间

Android OpenGL 以触摸移动的方向旋转立方体