将参数传递为"const"的奇怪效果

Strange effect of passing parameter as `const`

本文关键字:quot 参数传递 const      更新时间:2023-10-16

考虑以下类:

  1. 子弹类
class Bullet : public sf::Drawable {
public:
Bullet(const sf::Vector2f& pos, const sf::Vector2f& dir, 
const float& speed, const float& time, const float& life_time);
~Bullet();

bool collides(const Wall &wall);
private:
...
}

和墙壁类

class Wall : public sf::Drawable {
public:
Wall(const sf::Vector2f & endpoint1, const sf::Vector2f& endpoint2);
void sample();
~Wall();
private:
...
}

出于某种原因,我无法完全理解,当存在const时,我无法为bool collides(const Wall &wall)方法的wall参数调用任何方法,例如,如果我删除 const,一切正常。

我认为这可能与继承sf::Drawable有关,但我对SFML还没有经验。

有人可以澄清我应该调查什么以找出导致这种情况的原因吗? 提前谢谢你。

不能对const对象调用非 const 成员函数或对const对象的引用,就这么简单。

class Wall : public sf::Drawable {
public:
void sample() const; // <---- you need this
};            

现在由你决定,要么你让不改变状态的成员函数const,要么去掉collides参数的恒常性。