gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:51:32 24 4
gpt4 key购买 nike

我几乎完成了这个程序,但我一直得到一个极端的负数,并且无法弄清楚为什么。它像它应该的那样为每次加速和减速调用减去和增加 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;
}

最佳答案

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

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

speed 正在 default initialized这意味着它将有一个不确定的值并且在没有初始化的情况下使用它将会是undefined behavior .

关于c++ - 调用汽车类时的极端负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com