Error: taking address of temporary [-fpermissive]

后端 未结 3 895
生来不讨喜
生来不讨喜 2021-02-04 05:36

I\'ve been looking into this for a few hours, to no avail. Basically I have

struct rectangle {
    int x, y, w, h;
};

rectangle player::RegionCoordinates() // R         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 05:59

    RegionCoordinates() returns an object by value. This means a call to RegionCoordinates() returns a temporary instance of rectangle. As the error says, you're trying to take the address of this temporary object, which is not legal in C++.

    Why does IsCollision() take pointers anyway? It would be more natural to take its parameters by const reference:

    bool IsCollision (const rectangle &r1, const rectangle &r2) {
    if (r1.x < r2.x + r2.w &&
        r1.x + r1.w > r2.x &&
        r1.y < r2.y + r2.h &&
        r1.y + r1.h > r2.y) {
            return true;
        }
            return false;
    }
    //blah blah main while loop
    if (IsCollision(player1.RegionCoordinates(), stick1.RegionCoordinates())) //no error any more
    {
    player1.score+=10;
    stick1.x = rand() % 600+1;
    stick1.y = rand() % 400+1;
    play_sample(pickup,128,128,1000,false);
    }
    

提交回复
热议问题