我有一个 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/