c++ - 错误: taking address of temporary [-fpermissive]

标签 c++ collision-detection collision allegro

我已经研究了几个小时,但没有结果。基本上我有

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

rectangle player::RegionCoordinates() // Region Coord
{
    rectangle temp;
    temp.x = colRegion.x + coordinates.x;
    temp.w = colRegion.w;
    temp.y = colRegion.y + coordinates.y;
    temp.h = colRegion.h;

    return temp;
}

// Collision detect function
bool IsCollision (rectangle * r1, 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())) //ERROR
{
    player1.score+=10;
    stick1.x = rand() % 600+1;
    stick1.y = rand() % 400+1;
    play_sample(pickup,128,128,1000,false);
}

有什么想法吗?我确信这是非常明显的事情,但我一生都无法弄清楚。

最佳答案

RegionCooperatives() 按值返回对象。这意味着对 RegionCooperatives() 的调用会返回 rectangle 的临时实例。正如错误所示,您正在尝试获取此临时对象的地址,这在 C++ 中是不合法的。

为什么 IsCollision() 无论如何都要采用指针?通过 const 引用获取其参数会更自然:

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

关于c++ - 错误: taking address of temporary [-fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481490/

相关文章:

c++ - 零星碰撞检测

algorithm - 3D 碰撞/物体检测如何工作?

ipad - Spritekit (iOS 7) 是否有像素完美的碰撞检测?

java - 使用 HashMap 通过迭代更新值来计算 map 是一种好习惯吗?

C#:属性/字段命名空间歧义

c++ - 在 C++ 中存储运行时变量

c++ - 使用 fstream 从文件中获取最后一个字节的最佳方法?

c# - 使用通配符检查文件名搜索模式中的冲突

c++ - 为什么 multiset 保留重复元素的单独实例而不是它们的数量?

C++文件流