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

Ram*_*har 0 c++ opengl-es openframeworks

我有一个bars包含几个彩色框对象的向量.每个框对象都有自己的绘图和更新功能.每个盒子从屏幕的一侧移动到下一侧.当它在屏幕外时,应该移除该框.我正在使用迭代器移动框并确定它们何时在屏幕之外.

我对c ++很新,我无法让代码工作.从向量中擦除对象的功能给了我错误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); 
};
Run Code Online (Sandbox Code Playgroud)

在我的game.mm文件中,我创建了矢量并迭代它以设置彩色条形对象的属性:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新功能可在屏幕上移动条形图.

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()));

}
Run Code Online (Sandbox Code Playgroud)

这是检查框是否超出范围的功能

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我怎么解决这个问题?

jua*_*nza 5

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

Colorbar cb;
game::checkBounds(cb);
Run Code Online (Sandbox Code Playgroud)

它需要绑定到其类的实例,否则将无法访问该实例的其他成员.所以你需要将checkBounds成员函数绑定到一个实例game.在您的情况下,this看起来像绑定的正确实例:

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

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