一个类中多个对象的构造函数

Constructor for multiple objects in a class

本文关键字:对象 构造函数 一个      更新时间:2023-10-16

因此,我正在编写的程序要求我使用构造函数输入对象(漫游者)的初始值,而我无法找出正确的语法,以便它要求我输入输入坐标和方向的每一步。如果有人能告诉我如何制作,我将不胜感激。

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