类介绍 (c++) 项目希望我们创建两个构造函数,但它们都不需要任何参数 - 我应该在这里做什么?

Intro to classes (c++) project wants us to create two constructors, but neither of them need any parameters - what should i do here?

本文关键字:不需要 任何 参数 我应该 什么 在这里 构造函数 项目 希望 c++ 我们      更新时间:2023-10-16

我想我只是对这个项目的措辞感到困惑,但我在这里发布以确保我有正确的课程基础知识(就像我说的,我们刚刚开始学习它们)。

项目提示的开头如下:

声明并定义一个名为 Oddometer 的类。该类将有两个私人变量,一个用于行驶里程,另一个用于泵入汽车的加仑汽油。

成员函数应包括:

  • 一个构造函数,它采用两个私有变量的初始值。
  • 将两个值都设置为零的默认构造函数。

以及更多对我的问题不重要的成员函数。我完全理解默认构造函数,但另一个是我遇到麻烦的构造函数。如果他(我的教授)希望我们收集初始变量,那么为什么它根本不需要任何参数呢?我想我可以将一个空字符串作为参数传递到其中,但我觉得这里缺少一些东西......

为了扩展这个项目的重点,如果需要,我们正在创建一个程序,允许用户连续输入(在菜单屏幕上)行驶的英里数或放入油箱的加仑数。然后,当用户请求时,程序将找到 mpg。很简单。

这是程序的一部分,应该足以让有人帮助我解决这个问题。第二个/非默认构造函数似乎可以工作,除了显然我需要某种类型的参数。任何建议或帮助将不胜感激。

#include <iostream>
using namespace std;
class Odometer{
public:
Odometer(); // sets values to 0
Odometer(WHAT GOES HERE);    // gathers initial values
void get_miles();
void get_gallons();
void add_in_trip_miles();
void add_gas();
private:
double milesDriven;     // represents the miles the car has driven
double gallonsGas;      // represents the number of gallons pumped into car
};

int main() {
Odometer userInfo; // creates object for the user-inputted values
bool quit = false; // true when user wants to quit
int userChoice;    // for navigating the menu screen
while(!quit){
cout << "To view total miles, enter 1. To view total gallons, enter 2.nTo record more miles driven, enter 3. To record gallons pumped into the tank, enter 4.n To view the average MPG, enter 5. To reset the odometer, enter 6.n To quit the program, enter 7." << endl;
cin >> userChoice;
if(userChoice == 1) userInfo.get_miles(); // TODO: switch/case statement instead?
if(userChoice == 2) userInfo.get_gallons();
if(userChoice == 3) userInfo.add_in_trip_miles(); // TODO: "function which increases the miles by the amount sent in its parameter
}
cout << "Have a nice day!" <<endl;
return 0;
}

Odometer::Odometer(){   // sets values to 0 (default)
milesDriven = 0;
gallonsGas = 0;
}
Odometer::Odometer(WHAT GOES HERE?){     // gathers initial values
cout << "Please enter an initial value for miles driven." << endl;
cin >> milesDriven;
cout << "Please enter an initial value for how many gallons were put into the car." << endl;
cin >> gallonsGas;
}

你的老师要求你用参数实现第二个构造函数,以便用户能够用他想要的状态初始化对象。我会像这样实现它:

Odometer(double milesDriven_, double gallonsGas_) :
milesDriven(milesDriven_),
gallonsGas(gallonsGas_)
{}
相关文章: