呼叫汽车舱时出现极端负数
Extreme negative number when calling car class
我几乎完成了这个程序,但我一直得到一个极端的负数,不知道为什么。它对每一次加速和减速都会进行减法和加法运算,就像它应该做的那样,但速度的初始值太低了。
//头文件
#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
是默认初始化的,这意味着它将有一个不确定的值,在不初始化的情况下使用它将是未定义的行为。
相关文章:
- 呼叫运营商<<临时
- 呼叫 QSound,它们之间有延迟 Qt C++
- 我可以从标准::访问返回汽车吗?
- 什么是呼叫说明
- 汽车仪表模拟器
- 范围TS成语和神秘的汽车&&
- 为什么make_shared在不同的呼叫中分配相同的地址?
- 错误:类型"std::__1::basic_string<char>"不提供呼叫运算符
- 设备IO控制呼叫崩溃
- 根据呼叫位置进行记忆
- 成员呼叫通过接线员<<
- QSerialPort 手动 RTS 开/关未同步呼叫
- 将清除共享智能指针上的呼叫重置
- 来自 Pharo Smalltalk 的 ffi 呼叫上的分段错误
- C/C++ 在条件和阻止呼叫之间收到信号情报
- 将数据集从 R 传递到C++(使用 .呼叫)
- 无匹配函数呼叫getline()
- 通过呼叫constexpr函数来定义静态constexpr成员
- 组件X86转换为ARM功能呼叫,其中有不同数量的参数为ARM
- 呼叫汽车舱时出现极端负数