将参数传递为"const"的奇怪效果
Strange effect of passing parameter as `const`
考虑以下类:
- 子弹类
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
参数的恒常性。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数