为什么不在范围内声明制动和加速?

时间:2016-08-03 05:11:49

标签: c++

嘿伙计,所以我被分配来调试和修复给定的代码。在我们修复它之后,这个赋值应该是这样的: 在创建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");

}

2 个答案:

答案 0 :(得分:4)

应该是

first.Accelerate(speed)

这是Accelerate

的声明
int Car::Accelerate(int aSpd)

Car的方法以int为参数。

但你正在做的是:

Accelerate(first)

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

答案 1 :(得分:0)

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

当您在Accelerate函数中使用Breakmain时,它们将被称为自由函数,这些函数不存在。

在您的情况下,传递给AcceleateBreak的值无关紧要,因为参数被覆盖且从未使用过:

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