class 中多个对象的构造函数

Constructor for multiple objects in a class

所以我正在编写的程序要求我使用构造函数输入对象(漫游者)的初始值,我无法找出正确的语法来要求我输入输入的每个步骤坐标和方向。如果有人能告诉我怎么做,将不胜感激。

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;
}

您对构造函数的实现应该比这简单得多。只需使用输入参数初始化成员变量。

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);
}