嘿伙计,所以我被分配来调试和修复给定的代码。在我们修复它之后,这个赋值应该是这样的: 在创建Car对象的程序中演示类,然后调用加速 功能五次。每次调用加速功能后,获取当前的速度 汽车并显示它。然后,调用制动功能六次。每次调用制动器后 功能,获取当前车速并显示
这就是我所拥有的 - 问题是一旦它运行我就会收到错误说"加速"并且"制动器未在此范围内声明"这很奇怪,因为他们的功能应该放在正确的位置。如果我错过了什么,请告诉我!
#include <math.h>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
using namespace std;
class Car
{
private:
int YearModel;
int Speed;
string Make;
public:
Car(int, string, int);
string getMake();
int getModel();
int getSpeed();
int Accelerate(int aSpd);
int Brake(int bSpd);
void displayMenu();
};
Car::Car(int YearofModel, string Makeby, int Spd)
{
YearModel = YearofModel;
Make = Makeby;
Speed = Spd;
}
string Car::getMake()
{
return Make;
}
//To get the year of the car.
int Car::getModel()
{
return YearModel;
}
//To holds the car actual speed.
int Car::getSpeed()
{
return Speed;
}
//To increase speed by 5.
int Car::Accelerate(int aSpd)
{
aSpd = Speed;
Speed = Speed + 5;
return aSpd;
}
//To drop the speed of the car by 5.
int Car::Brake(int bSpd)
{
bSpd = Speed;
Speed = Speed - 5;
return bSpd;
}
void displayMenu()
{
cout << "\n Menu\n";
cout << "----------------------------\n";
cout << "A)Accelerate the Car\n";
cout << "B)Push the Brake on the Car\n";
cout << "C)Exit the program\n\n";
cout << "Enter your choice: ";
}
int main()
{
int Speed = 0; //Start Cars speed at zero.
char choice; //Menu selection
int year;
string carModel;
cout << "Enter car year: ";
cin >> year;
cout << "Enter the car model(without spaces): ";
cin >> carModel;
Car first(year, carModel, Speed);
//Display the menu and get a valid selection
do
{
displayMenu();
cin >> choice;
while (toupper(choice) < 'A' || toupper(choice) > 'C')
{
cout << "Please make a choice of A or B or C:";
cin >> choice;
}
//Process the user's menu selection
switch (choice)
{
case 'a':
case 'A': cout << "You are accelerating the car. ";
cout << Accelerate(first) << endl;
break;
case 'b':
case 'B': cout << "You have choosen to push the brake.";
cout << Brake(first) << endl;
break;
}
}while (toupper(choice) != 'C');
return 0;
system("pause");
}
答案 0 :(得分:4)
应该是
first.Accelerate(speed)
这是Accelerate
:
int Car::Accelerate(int aSpd)
Car
的方法以int
为参数。
但你正在做的是:
Accelerate(first)
这是一个函数调用(对于一个名为Accelerate
的函数,它是未声明的),你传递的是Car
。
答案 1 :(得分:0)
由于Accelerate
和Break
是Car
的函数,因此必须在Car
对象上调用它们:first.Accelerate(42)
。
当您在Accelerate
函数中使用Break
和main
时,它们将被称为自由函数,这些函数不存在。
在您的情况下,传递给Acceleate
和Break
的值无关紧要,因为参数被覆盖且从未使用过:
int Car::Accelerate(int aSpd)
{
aSpd = Speed;
// ...
}