2016-03-26 37 views
-2

如何在下面的代碼中使用另一個函數中的lastLoc對象的x和y值。我沒有得到任何錯誤,但是當我在getPosLoc功能打印lastLoc的價值觀,我得到一個較長的數字(可能是地址):如何在另一個函數中使用類對象? C++

class solveMaze { 
private: 
    maze maze; 
    mouse m; 
    stack<coords> coordStack; 
    int x; 
    int y; 
    int posLocCount = 0; 
    coords lastLoc; 
}; 

solveMaze::solveMaze() { 
    x = m.x; 
    y = m.y; 
    coords c(x, y); 
    coords lastLoc(c.x, c.y); 
    coordStack.push(c); 
} 

void solveMaze::getPosLoc() { 
    if((mazeLayout[x][y-1] == 0) && (x != lastLoc.x) && (y-1 != lastLoc.y)) { 
     posLocCount++; 
     putUp(); 
    } 

這是去掉無關的功能coords.h縮短代碼:

class coords { 
    public: 
     coords(){}; 
     coords(int, int); 
     int x; 
     int y; 
     friend ostream &operator<<(ostream &output, const coords &c); 
     bool operator==(coords); 
     void operator=(const coords &b); 
}; 


coords::coords(int a, int b) { 
    x = a; 
    y = b; 
} 

這是mouse.h:

class mouse { 
    private: 
     maze maze; 
    public: 
     mouse(); 
     int x; 
     int y; 
}; 

mouse::mouse() { 
    for (int i=0; i<12; i++) { 
     for (int j=0; j<29; j++) { 
      if (mazeLayout[i][j] == 8){ 
       x = j; 
       y = i; 
      } 
     } 
    } 
} 
+0

'x = m.x;'< - 我沒有看到你在該行之前初始化'm'。什麼是默認構建的'鼠標'應該包含? – Michael

回答

2

有幾個明顯的問題:

  1. coords lastLoc(c.x, c.y);

此語句聲明並初始化一個名爲lastLoc局部變量...這是指成員lastLoc。對於該代碼需要

lastLoc = coords(c.x, c.y); 
  1. x = m.x;y = m.y;

這些語句用m尚未明確地初始化,如何定義了類?

+0

啊謝謝你的工作 – nanjero

-1

你應該爲x和y製造吸氣劑和吸附劑,因爲這是更好的做法。但是如果你想引用coord的x或y。你應該寫:

lastLoc->x 
+1

爲什麼? 「lastLoc」在哪裏聲明爲指針? – Michael

相關問題