2015-12-07 58 views
0

所以我寫的程序需要我使用構造函數輸入對象(流動站)的初始值,我無法弄清楚正確的語法以便它讓我輸入每個輸入座標和方向的步驟。如果任何人能夠告訴我如何做到這一點,將不勝感激。一個類中的多個對象的構造函數

class Rover{ 

private: 

    string name; 
    int xpos; 
    int ypos; 
    string direction; //Use Cardinal Directions (N,S,E,W) 
    int speed; //(0-5 m/sec) 

public: 
    //Constructors 
    Rover(int,int,string,int); 
}; 
Rover::Rover(int one, int two, string three, int four) 
    { 
     cout<<"Please enter the starting X-position: "; 
     cin>>one; 
     cout<<"Please enter the starting Y-position: "; 
     cin>>two; 
     cout<<"Please enter the starting direction (N,S,E,W): "; 
     cin>>three; 
     cout<<"Please enter the starting speed (0-5): "; 
     cin>>four; 

     xpos=one; 
     ypos=two; 
     direction=three; 
     speed=four; 

     cout<<endl; 
    } 

int main(int argc, char** argv) { 

    int spd; 
    string direct; 
    string nme; 
    int x; 
    int y; 


    Rover r1(int x,int y, string direct, int spd); 
    Rover r2(int x,int y, string direct, int spd); 
    Rover r3(int x,int y, string direct, int spd); 
    Rover r4(int x,int y, string direct, int spd); 
    Rover r5(int x,int y, string direct, int spd); 






    return 0; 
} 
+2

re「需要我使用構造函數輸入對象(流動站)的初始值」,您確定*這是對要求的正確解釋嗎?在構造函數中執行I/O通常是不好的做法。一方面,這意味着如果不進行大量修改就不能重用代碼。 –

+0

這不是正確的構造函數。爲了實現你的目標,你需要先獲得這些值(x,y,方向和速度),然後調用構造函數,提供這些參數。 – SergeyA

+0

因爲工作表所說的是我需要編寫一個構造函數,它可以處理所有5個參數(名稱,x,y,方向,速度)並將它們初始化 – John

回答

0

您的構造函數的實現應該比這更簡單。只需使用輸入參數初始化成員變量即可。

Rover::Rover(int xp, int yp, string dir, int sp) : 
    xpos(xp), ypos(yp), direction(dir), speed(sp) {} 

讀取輸入然後使用輸入構建對象的代碼可以移動到不同的函數,最好是非成員函數。

Rover readRover() 
{ 
    int xp; 
    int yp; 
    string dir; 
    int sp; 

    cout << "Please enter the starting X-position: "; 
    cin >> xp; 

    cout << "Please enter the starting Y-position: "; 
    cin >> xp; 

    cout << "Please enter the starting direction (N,S,E,W): "; 
    cin >> dir; 

    cout << "Please enter the starting speed (0-5): "; 
    cin >> sp; 

    // Construct an object with the user input data and return it. 
    return Rover(xy, yp, dir, sp); 
} 

,然後從main使用readRover多次如你所願。

Rover r1 = readRover(); 
Rover r2 = readRover(); 
Rover r3 = readRover(); 
Rover r4 = readRover(); 
Rover r5 = readRover(); 

函數readRover假定用戶提供了正確的輸入。如果用戶沒有提供正確的輸入,你的程序將被卡住,唯一的出路將是使用Ctrl + C或其他等價物來中止程序。

要處理用戶錯誤,您需要添加代碼來首先檢測錯誤,然後決定如何處理錯誤。

if (!(cin >> xp)) 
{ 
    // Error in reading the input. 
    // Decide what you want to do. 
    // Exiting prematurely is an option. 
    std::cerr << "Unable to read x position." << std::endl; 
    exit(EXIT_FAILURE); 
} 
+0

現在,我已經所有的閱讀漫遊器如何去打印它們在主數組中。我不知道如何從漫遊車1移動到漫遊車2等等 – John

相關問題