呼叫汽车舱时出现极端负数

Extreme negative number when calling car class

本文关键字:汽车 呼叫      更新时间:2023-10-16

我几乎完成了这个程序,但我一直得到一个极端的负数,不知道为什么。它对每一次加速和减速都会进行减法和加法运算,就像它应该做的那样,但速度的初始值太低了。

//头文件

#ifndef CAR_H
#define CAR_H
#include <string>
#include <cctype>
#include <iomanip>
#include <cstdlib>
class Car
{
private:
int yearModel;
std::string make;
int speed;
public:
Car(int, std::string);
int getYearModel() const
{ return yearModel; }
std::string getMake() const
{ return make; }
int getSpeed() const
{ return speed; }
void accelerate();
void brake();
};
#endif

//实现cpp文件

#include "Car.h"
#include <iostream>
using namespace std;
Car::Car(int y, string m)
{
yearModel = y;
make = m;
}
void Car::accelerate()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}

//主程序文件

#include <iostream>
#include "Car.h"
#include <string>
using namespace std;
int main()
{
int yearModel, speed;
string make;
cout << "Enter the year and make of this car." << endl << endl;
cout << "Year of Model (between 1980 and 2014):";
cin >> yearModel;
while ((yearModel < 1980) || (yearModel > 2014))
{
cout << "Invalid entry, enter a number between 1980 and 2014:";
cin >> yearModel;
}
cout << "Make:";
cin >> make;
Car charger(yearModel, make);
cout << "Car is at rest, currently traveling at " << charger.getSpeed() << " miles per hour, pressing accelerator." << endl << endl;
for (int i = 0; i < 5; i++)
{
charger.accelerate();
cout << "Current speed is " << charger.getSpeed() << " miles per hour" << endl;
system("pause");
}
cout << "Now pressing brake" << endl;

for (int i = 0; i < 5; i++)
{
charger.brake();
cout << "Current speed is " << charger.getSpeed() << " miles per hour" << endl;
system("pause");
}

system("pause");
return 0;
}

您没有在构造函数中初始化speed,它不会被零初始化,它将被构造Car对象的内存块中的一个不确定值初始化。只需在构造函数中将其初始化为零,您就可以了:

Car::Car(int y, string m) : yearModel(y), make(m), speed(0) {}
^^^^^^^^

speed是默认初始化的,这意味着它将有一个不确定的值,在不初始化的情况下使用它将是未定义的行为。