【问题标题】:Cannot convert 'this' pointer from 'const Bullet' to 'Bullet &'无法将“this”指针从“const Bullet”转换为“Bullet &”
【发布时间】:2013-11-18 03:38:48
【问题描述】:

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

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

【问题讨论】:

  • 您是否尝试过将您使用的函数定义为 const?您使用 const 迭代器。stackoverflow.com/questions/309581/…,如果您通过调用成员函数使用迭代器更改某些内容,可能会导致问题,请尝试“cout

标签: c++ list


【解决方案1】:

您需要将detectCollision 声明为const

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

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

【讨论】:

  • 谢谢。花了一些工作来修复添加 const 导致的错误,但它可以工作。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2011-09-30
      • 2021-06-11
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多