我是c ++的新手,并试图创建一个汽车类程序,要求用户一年和汽车制造。然后程序采取速度,始终从0开始,加速5mph 5次,并以5英里/小时制动5次。我必须使用头文件和2个cpp文件创建程序。速度的返回值不正确,并显示为:
输入汽车年份:2000 输入汽车的品牌:雪佛兰 起跑速度为-858993460
目前的速度是:-858993455英里/小时。
目前的速度是:-858993450英里每小时。
目前的速度是:-858993445英里/小时。
目前的速度是:-858993440英里/小时。
目前的速度是:-858993435英里每小时。
目前的速度是:-858993440英里/小时。
目前的速度是:-858993445英里/小时。
目前的速度是:-858993450英里每小时。
目前的速度是:-858993455英里/小时。
目前的速度是:-858993460英里每小时。
按任意键继续。 。
任何人都可以帮我弄清楚我做错了什么吗?到目前为止,我已经附上了我的内容。任何帮助是极大的赞赏。感谢
#define CAR_H
#include <string>
using namespace std;
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car(int, string);
void accelerate();
void brake();
int getSpeed ();
};
#include <iostream>
#include "Car.h"
using namespace std;
Car::Car(int carYearModel, string carMake)
{
int yearModel = carYearModel;
string make = carMake;
int speed = 0;
}
void Car::accelerate()
{
speed += 5;
}
void Car::brake()
{
speed -= 5;
}
int Car::getSpeed()
{
return speed;
}
int getYear(int year)
{
return year;
}
string getMake(string make)
{
return make;
}
#include "Car.h"
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
int count;
int yr;
string mk;
int getSpeed;
cout << "Enter the year of the car: ";
cin >> yr;
cout << "Enter the make of the car: ";
cin >> mk;
Car myCar(yr, mk);
cout << "The starting speed is "
<< myCar.getSpeed() << endl << endl;
for ( count = 0; count < 5; count++)
{
myCar.accelerate();
cout << "The current speed is: " << myCar.getSpeed()
<< " mph." << endl;
}
for ( count = 0; count < 5; count++)
{
myCar.brake();
cout << "The current speed is: " << myCar.getSpeed()
<< " mph." << endl;
}
system ("pause");
return 0;
}
答案 0 :(得分:7)
在此代码中:
Car::Car(int carYearModel, string carMake)
{
int yearModel = carYearModel;
string make = carMake;
int speed = 0;
}
您没有分配给Car
对象的数据成员。相反,您要声明与字段名称相同的局部变量,然后分配给这些局部变量。
要解决此问题,请删除类型:
Car::Car(int carYearModel, string carMake)
{
yearModel = carYearModel;
make = carMake;
speed = 0;
}
希望这有帮助!