2015-12-07 61 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

相关问题