为什么没有在范围内宣布制动和加速

Why isnt Brake and Accelerate declared in scope?

本文关键字:布制动 加速 范围内 为什么      更新时间:2023-10-16

嘿,伙计们,所以我被指派调试和修复给定的代码。在我们修复后,此任务应按如下方式工作:在创建Car对象的程序中演示类,然后调用加速功能五次。每次调用加速函数后,获取然后,调用刹车功能六次。每次刹车后功能,获取汽车的当前速度并将其显示

这就是我的问题——问题是,一旦它运行,我就会收到一个错误,说"加速"answers"刹车没有在这个范围内声明",这很奇怪,因为它们是应该放在正确位置的功能。如果我错过了什么,请告诉我,谢谢!!!

#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 Menun";
   cout << "----------------------------n";
   cout << "A)Accelerate the Carn";
   cout << "B)Push the Brake on the Carn";
   cout << "C)Exit the programnn";
   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");
}

应该是

first.Accelerate(speed)

这是Accelerate:的声明

int Car::Accelerate(int aSpd)

它是Car的一个方法,它以int为自变量。

但你正在做的是:

Accelerate(first)

这是一个函数调用(对一个未声明的名为Accelerate的函数),您将向它传递一个Car

由于AccelerateBreakCar的函数,因此必须在Car对象上调用它们:first.Accelerate(42)

main函数中使用AccelerateBreak时,它们被称为不存在的自由函数。


在您的情况下,传递给AcceleateBreak的值并不重要,因为参数会被覆盖并且从未使用过:

int Car::Accelerate(int aSpd)
{
   aSpd = Speed;
   // ...
}