2016-02-06 98 views
0

我目前正在編寫一個程序,允許用戶輸入一個方向並沿着座標平面移動一個機器人。我是C++的新手,所以我得到的一些錯誤讓我感到困惑。有人可以解釋我的錯誤嗎?C++函數參數和結構錯誤

當我調用函數init_room時,它表示參數太少。當我調用init_robot時會發生同樣的事情。他們都有指針參數。我將如何解決這個問題?

當我調用函數在主函數中移動時,它說表達式必須是可修改的值。這是什麼意思?

感謝您的幫助!

#include <iostream> 

using namespace std; 

typedef struct room { 
    int x; 
    int y; 
}; 

typedef struct robot { 
    room *current_room; 
    int current_x; 
    int current_y; 
    int model; 
}; 

void init_robot(robot *r) { 
    r->current_room->x; 
    r->current_room->y; 
    r->current_x = 0; 
    r->current_y = 0; 
    //Assign model number 
    r->model; 
} 

void init_room(room *r) { 
    cin >> r->x; 
    cin >> r->y; 

} 

char move(robot *r, int direction) { 
     if (direction == 'N' || direction == 'n') 
     { 
      r->current_y + 1; 
     } 
     else if (direction == 'S' || direction == 's') 
     { 
      r->current_y - 1; 
     } 
     else if (direction == 'E' || direction == 'e') 
     { 
      r->current_x + 1; 
     } 
     else if (direction == 'W' || direction == 'w') 
     { 
      r->current_x - 1; 
     } 
     else 
     { 
      direction = 'x'; 
      return direction; 
     } 

    int main() { 
     char direction; 
     char restart; 

     cout << "What size would you like the room to be?"; 

     room rr; 

     init_room(); 

     robot r; initrobot(); 

     while (true) { 

       cout << "Your robot is in a room with the dimensions (" << rr.x << "," << rr.yy << "). at location (" << r.current_x << "," << r.current_y << ")." << endl; 
       cout << "What direction would you like to move? N (North), E (east), S(South), or W(West)?"; 
       do { 
       cin >> direction; 

       move(direction) = direction; 
       if (direction = 'x') { 
        cout << "Invalid direction. Please enter N, E, S, or W."; 
        } 
       while (direction == 'x'); 

       cout << "Current position is" << endl; 

    //   if (r.current_x <= rr.x && r.current_y <= rr.y) 
     //  { 
      //  cout << "Error, your robot is out of the room bounds. Your robot has exited the room. Would you like to enter another room? Y or N?"; 
        cin >> restart; 
      //} while (restart == 'Y' || restart == 'y'); 
        } 

      system("pause"); 
      return 0; 
     } 

回答

2

函數init_room和init_robot每個都只有一個參數。所以,你對他們的調用應該像

init_room(&rr); 
init_robot(&r); 

move返回char類型的右值,而右值不能被修改。它只能用作其他表達式的輸入。我希望你不知道什麼是右值,因此它是一個很好的主意,因爲它是C++中的一個重要概念。 (快速版本:一個右值可能在=的右側,基本上是隻讀的。)

+1

謝謝你們的幫助! @GaryMakin我肯定會研究一下右值是什麼。謝謝你的提示。 – starlight