2

我正在尝试为我的项目符号使用列表。每当我运行我的更新项目符号代码时,它都会给我这个错误:

错误 1 ​​错误 C2662:“Bullet::detectCollision”:无法将“this”指针从“const Bullet”转换为“Bullet &”

我的列表:

std::list<Bullet> bullet_list;

我的更新代码:

std::list<Bullet>::const_iterator cIter;
    for ( cIter = bullet_list.begin( ); cIter != bullet_list.end( ); cIter++ )
    {
        if((*cIter).detectCollision(monster.position,monster.getHeight(),monster.getWidth()))
        {
//Do stuff here
        }
        if ((*cIter).detectCollision(boss.getPosition(),boss.getHeight(),boss.getWidth()))
        {
//Do stuff here
        }
    }

我检测碰撞代码:

bool Bullet::detectCollision(Vector objTwo,int heightT,int widthT)
{
if(position.getVectorX() >= objTwo.getVectorX() - (widthT/2) && position.getVectorX() <= objTwo.getVectorX() + (widthT/2)
    && position.getVectorY() >= objTwo.getVectorY() - (widthT/2)&& position.getVectorY() <= objTwo.getVectorY() + (heightT/2) && alive)
{
    return false;
}
return true;
}
4

3 回答 3

4

您需要声明detectCollisionconst.

bool Bullet::detectCollision(Vector objTwo,int heightT,int widthT) const

如果您不这样做,它会尝试进行转换,以便它可以在 const 引用上调用非常量函数,但这是不允许的。

于 2013-11-06T18:33:08.190 回答
1

您正在使用 const_iterator 但尝试访问非常量成员函数。使用迭代器而不是 const_iterator 或将函数声明为 const(如果它可以是 const 成员函数)。

于 2013-11-06T18:35:39.110 回答
0

Aconst_iter不允许更改它指向的值,因此当您调用时,detectCollision您需要向编译器保证您也不会更改这些值(生成函数const)。

于 2013-11-06T18:33:19.417 回答