即使使用引用,函数也不会更改C++中的对象属性
我正在尝试ball通过调用函数来更改s 位置
struct ball
{
int heading = north_east;
bool visible = true;
int pos_x = ball_start_x;
int pos_y = ball_start_y;
char c = 'o';
};
void move_ball(ball *target_ball)
{
switch (target_ball->heading)
{
case north_east:
{
target_ball->pos_x ++ ;
target_ball->pos_y -- ;
}
case north_west:
{
target_ball->pos_x -- ;
target_ball->pos_y -- ;
}
case south_west:
{
target_ball->pos_x ++ ;
target_ball->pos_y ++ ;
}
case south_east:
{
target_ball->pos_x -- ;
target_ball->pos_y ++ ;
}
}
}
int main(){
ball ball_no_1;
move_ball(&ball_no_1);
}
但即使我通过引用调用它们,位置似乎也没有改变!
请帮我...
回答
你忘了一堆break语句,case north_east后面的所有行都执行了,加二减二的结果是0
switch (target_ball->heading)
{
case north_east:
{
target_ball->pos_x ++ ;
target_ball->pos_y -- ;
break;
}
case north_west:
{
target_ball->pos_x -- ;
target_ball->pos_y -- ;
break;
}
case south_west:
{
target_ball->pos_x ++ ;
target_ball->pos_y ++ ;
break;
}
case south_east:
{
target_ball->pos_x -- ;
target_ball->pos_y ++ ;
break;
}
}