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

Strange effect of passing parameter as `const`

考虑以下 classes :

  1. 子弹class
    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

    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 参数调用任何方法,例如如果我删除常量,一切正常。

我认为这可能与继承 sf::Drawable 有关,但我对 SFML 还不是很熟悉。

有人可以阐明我应该调查什么来找出造成这种情况的原因吗? 提前谢谢你。

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

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

现在由你决定,要么将不改变状态的成员函数设为 const,要么摆脱 collides.

参数的常量性