呼叫汽车类时极端负数

时间:2014-01-28 22:46:46

标签: 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::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;
}

1 个答案:

答案 0 :(得分:6)

您没有在构造函数中初始化speed,它不会被初始化为零,它将使用构造Car对象的内存块中的不确定值进行初始化。只需初始化它在构造函数中为零,你应该没问题:

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

speed正在default initialized,这意味着它将具有不确定值,并且在未初始化的情况下使用它将是undefined behavior