C++ 调用汽车类时的极端负数

C++ 调用汽车类时的极端负数,c++,class,negative-number,C++,Class,Negative Number,我几乎完成了这个程序,但我一直得到一个极端的负数,我不知道为什么。它会像应该的那样,为每次加速和减速调用减法和加5,但速度的初始值太低 //头文件 #ifndef CAR_H #define CAR_H #include <string> #include <cctype> #include <iomanip> #include <cstdlib> class Car { private: int yearModel; std::

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

//头文件

#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;
}
您没有在构造函数中初始化速度,它将不会初始化为零,它将使用构造汽车对象的内存块中的不确定值进行初始化。只需在构造函数中将其初始化为零,就可以了:

Car::Car(int y, string m) : yearModel(y), make(m), speed(0) {}
                                                   ^^^^^^^^
速度为,这意味着它将有一个不确定的值,在没有初始化的情况下使用它将是。

如果没有在构造函数中初始化速度,它将不会初始化为零,它将使用构造汽车对象的内存块中的不确定值初始化。只需在构造函数中将其初始化为零,就可以了:

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

速度是存在的,这意味着它将有一个不确定的值,在没有初始化的情况下使用它将是不确定的。

因为速度从来没有初始化或分配过任何东西,所以使用它是不确定的行为。任意性比随机性更准确;后者有一个特定的统计含义。@ KeththoppsHMM,是的好点,另一个用户编辑它时,我在做一些变化中。我最初使用的是不定值。不定值可能比任意值更好。任意值比随机值更精确;后者有一个特定的统计含义。@ KeththoppsHMM,是的好点,另一个用户编辑它时,我在做一些变化中。我最初使用的是不定值。不定值可能比任意值更好。