2014-01-11 91 views
1

我正在爲一個大學項目設計一個機器人模擬器,並且我碰到了一個碰撞檢測的大問題。這是我的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,這就像我的程序正在創建兩個不同的變量。如果有人能夠揭示這種奇怪的行爲,那麼請告訴我!謝謝

+0

「默認值爲真」 - 不,默認值是未定義的。 – addaon

+0

在機器人上設置returnObject *變量的代碼在哪裏?矩陣碼在哪裏?什麼是您的調用代碼,以便您期望結果匹配? – addaon

+0

對不起,我會更新我的問題。 –

回答

1

您的程序製作了兩個不同的值,因爲它的具有兩個不同的值。 matrix類顯然有它自己的布爾變量,matrix::returnObjectDash,機器人類有它自己的變量,robot::returnObjectDash。在一個類的一個實例中設置變量對任何其他類(或任何其他實例)中的變量都沒有影響。

+0

好吧,所以想到這個邏輯,我將不得不在我的main.cpp中設置returnObject,他們都有權訪問它? –

+0

您可以使用他們都有權訪問的單個變量,是的。爲了達到這個目的,在技術層面上,你可以傳遞機器人實例和矩陣實例指針或引用到同一個變量。我沒有足夠的設計圖片來了解這是否是一個好的計劃。 – NicholasM

+0

我實際上正在考慮將它作爲一個指針,然後引用它,謝謝你也提出這個想法。謝謝。 –

1

您還沒有提供的代碼給你Matrix類的,不過,從void matrix::detection(int x, int y)判斷我以爲你在那裏的方法,叫做檢測,並且已經聲明相同的字段returnObjectLinereturnObjectDash

假設這些變量有兩個版本是正確的:其中一個版本位於矩陣對象內,另一個位於機器人對象內。

不僅如此,您可以(通常也可以!)擁有多個矩陣/機器人對象。每個人都有自己的這些變量的副本,改變其中的一個不會影響其他變量。

+0

Ahhh是的,關於擁有多於一個矩陣或機器人的好處。請參閱原始問題以獲取更新。 –