布尔值的奇怪行为

时间:2014-01-11 23:59:07

标签: c++ boolean simulator

我正在为大学项目设计一个机器人模拟器,我遇到了一些碰撞检测的大问题。这是我的robot.h头文件:

#ifndef robot_h
#define robot_h

#include <vector>

enum direction
{
    UP,DOWN,LEFT,RIGHT
};

enum motor
{
    STOP,SLOW,FAST
};

class robot
{
public:
    robot();

    char bot; // The bot onscreen
    int getX(); // The X position of robot
    int getY(); // The Y position of robot

    int dir; // The direction the robot is going

    bool touchSensor; // Boolean value if collision
    int lightSensor; // light sensor between 10-100
    int motorA; // Motor A between 0, 1 and 2
    int motorB; // Motor A between 0, 1 and 2
    void detection(int x, int y);

    void getReturnObject();
    bool returnObjectDash;
    bool returnObjectLine;

    void move(); // Moving the robot
    void draw(); // Drawing the robot on screen
    void update(); // Updating the robot position

private:
    int positionX; // Starting X value
    int positionY; // Starting Y value
};

#endif

基本上,我使用了两个布尔值: returnObjectDash;returnObjectLine。我在matrix.cpp文件中有这个代码:

void matrix::detection(int x, int y)
{
    if(vector2D[x][y]=='-')
    {
        returnObjectDash=true;
        system("pause");
    }
    else
    {
        returnObjectDash=false;
    }
    if(vector2D[x][y]=='|')
    {
        returnObjectLine=true;
    }
    else
    {
        returnObjectLine=false;
    }
}

在我的robot.cpp中,我有这个代码,它获取两个布尔值,然后输出到控制台:

void robot::getReturnObject()
{
    if(returnObjectDash==true)
    {
        std::cout<<"Dash\n";
        //dir=DOWN;
    }
    if(returnObjectLine==true)
    {
        std::cout<<"Line\n";
        //dir=DOWN;
    }
}

这是我的main.cpp

int main()
{
    robot r;

    while(true)
    {
        matrix m;
        m.robotPosition(r.getX(), r.getY());
        m.update(); // vector2D init and draw
        m.detection(m.getX(), m.getY());  
        r.update();
        Sleep(250);
    }
}

我在matrix.cpp默认构造函数中将我的两个布尔变量的默认值设置为false。当我点击暂停按钮并调试时,我似乎得到了两个不同的回报。对于我的矩阵,它返回false,但是对于我的机器人它返回true,就像我的程序正在制作两个不同的变量。如果有人可以对这种奇怪的行为有所了解,那么请告诉我们!谢谢

2 个答案:

答案 0 :(得分:1)

你没有为矩阵类提供代码,但是,从void matrix::detection(int x, int y)判断我假设你有一个方法,称为检测,并且你声明了相同的字段returnObjectLine和{ {1}}。

假设这些变量有2个版本是正确的:其中一个版本位于矩阵对象中,另一个版本位于机器人对象内。

不仅如此,您可以(并且通常会!)拥有多个矩阵/机器人对象。每个变量都有自己独立的副本,而更改其中一个变量不会影响其他变量。

答案 1 :(得分:1)

您的程序正在制作两个不同的值,因为它具有两个不同的值。 matrix类显然有自己的布尔变量matrix::returnObjectDash,机器人类有自己的变量robot::returnObjectDash。在一个类的一个实例中设置变量对任何其他类(或任何其他实例)中的变量没有影响。

相关问题