一个类中多个对象的构造函数
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);
}
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数