C++ 调用函数时,类对象成员变量不会更改
我的问题是我不能改变类成员的变量值,我尝试了我想到的一切 下面是涉及的代码:C++ 调用函数时,类对象成员变量不会更改,c++,class,member-variables,C++,Class,Member Variables,我的问题是我不能改变类成员的变量值,我尝试了我想到的一切 下面是涉及的代码: if(player.getCollisionObject().isColliding(platform1)) { if(player.getCollisionObject().up) std::cout << "Colliding from top\n"; if(player.getCollisionObject().down) std::cout <&
if(player.getCollisionObject().isColliding(platform1))
{
if(player.getCollisionObject().up)
std::cout << "Colliding from top\n";
if(player.getCollisionObject().down)
std::cout << "Colliding from bottom\n";
if(player.getCollisionObject().left)
std::cout << "Colliding from left\n";
if(player.getCollisionObject().right)
std::cout << "Colliding from right\n";
}
bool Collision::isColliding(const Entity &other)
{
resetCollisionDirection();
sf::Vector2f otherCenterPosition = other.getCenterPosition();
sf::Vector2f otherSize = other.getSize();
float deltaX = m_CenterPosition.x - otherCenterPosition.x; // abs(deltaX) - (thisX + otherX)
float deltaY = m_CenterPosition.y - otherCenterPosition.y;
float resultX = abs(deltaX) - (m_Size.x / 2 + otherSize.x / 2);
float resultY = abs(deltaY) - (m_Size.y / 2 + otherSize.y / 2);
if(resultX < 0 && resultY < 0)
{
if(m_CenterPosition.x < otherCenterPosition.x)
left = true;
if(m_CenterPosition.x > otherCenterPosition.x)
right = true;
if(m_CenterPosition.y < otherCenterPosition.y)
up = true;
if(m_CenterPosition.y > otherCenterPosition.y)
down = true;
return true;
}
return false;
}
class Collision
{
public:
Collision(const Entity &entity);
void reset(const Entity &entity);
bool isColliding(const Entity &other);
bool up, down, left, right;
private:
void resetCollisionDirection();
private:
sf::Vector2f m_CenterPosition, m_Size;
};
编辑:发现问题上面的函数返回了一个副本我是个白痴抱歉把它改成了
Collision& Player::getCollisionObject()
{
return m_CollisionBody;
}
这是你的问题。getCollisionObject按值返回。换成
Collision &Player::getCollisionObject()
使用调试器。在代码中的可疑位置放置断点,说明应该发生什么,然后查看实际发生的情况。向我们展示getCollisionObject函数。@alterigel我确实这样做了,这就是为什么我在这里,因为我找不到问题可能出在哪里!我一步一步地检查,因为我提到的每一项似乎都工作得很好,但一旦我从函数调用返回,实际上碰撞变量中没有设置任何内容@0x499602D2我添加了它,问题可能是因为它返回一个已设置的副本吗?@muhm这正是问题所在。您必须返回碰撞&。
Collision &Player::getCollisionObject()