質問

I have a vector bars that contains several coloured box objects.Each box object has it's own draw and update function. Each box moves from one side of the screen to the next side. when it's outside the screen the box should be removed. I'm using iterators to move the boxes and determine when they are outside of the screen.

I'm very new to c++ and I'm having trouble getting the code to work. the function to erase an object from a vector is giving me the error Reference to non static member function must be called. I'm reading up on static and non static members but I'm still a bit lost.

here's my main header file with the relevant code

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

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

in my game.mm file I create the vector and iterate over it to set the properties of the coloured bar objects:

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

the update function that move the bars across the screen.

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

}

and here's the function to check if the box is out of bounds

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;
    }
}

I've done some experimenting, and making the bool checkBounds (Colorbar &b); non-static by removing it from the header file makes the code work. but the problem is that I'd also like to be able to access the bars vector in that function to add a new object when an old one is deleted. And that won't work anymore.

How can I solve this?

役に立ちましたか?

解決

You need a unary functor taking a ColourBar. A member function has an implicit first parameter for this. This means it cannot be called like this:

Colorbar cb;
game::checkBounds(cb);

It needs to be bound to an instance of its class, otherwise it would not be able to access other members of that instance. So you need to bind the checkBounds member function to an instance of game. In your case, this looks like the right instance to bind:

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

using std::placeholders; // for _1
...
remove_if(bars.begin(), bars.end(), std::bind(&game::checkBounds, this, _1)) ...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top