【发布时间】:2016-11-13 20:59:34
【问题描述】:
我一直在拼命想弄清楚这个作业的“构造函数”部分。这包括阅读教科书和在线浏览。有人可以指出我正确的方向吗?下面的代码完美运行,只需要添加一个构造函数。
以下是此作业的说明: 车类说明:
编写一个名为“Car”的类,该类具有以下成员变量:
年。保存汽车型号年份的 int。
制作。保存汽车品牌的字符串对象。
速度。保存汽车当前速度的 int 对象。
此外,该类应具有以下成员函数:
构造函数。构造函数应该接受汽车的年份并制作成员变量。构造函数应该将这些值初始化为对象的年份并生成成员变量。构造函数应该将speed成员变量初始化为0。
访问器。应创建适当的访问器函数以允许从对象的年份、品牌和速度成员变量中检索值。
加速。每次调用时,加速函数都应将 speed 成员变量加 5。
刹车。每次调用刹车函数时,速度成员变量都应减去 5。
在程序中演示该类,该类创建一个 Car 对象,然后调用五次加速函数。每次调用加速函数后,获取汽车的当前速度并显示出来。然后,调用制动功能 5 次。每次调用刹车函数后,获取汽车当前的速度并显示出来。
#include<iostream>
#include<string>
using namespace std;
class Car
{
private:
int year;
string make;
int speed = 0;
public:
void setYear(int);
void setMake(string);
void setSpeed(int);
int getYear();
string getMake();
int getSpeed();
void accelerate();
void brake();
};
void Car::setYear(int y)
{year = y;}
int Car::getYear(){
return year;}
void Car::setMake(string m)
{make = m;}
string Car::getMake(){
return make;}
void Car::setSpeed(int spd)
{speed = spd;}
int Car::getSpeed(){
return speed;}
void Car::accelerate()
{speed +=5;}
void Car::brake()
{
if( speed > 5 )
speed -=5;
else speed = 0 ;
}
int main()
{
Car myCar;
int bYear = 0;
string bMake;
cout << "Please enter the year of the vehicle.\n";
cin >> bYear;
cout << "Please enter the make of the vehicle.\n";
cin >> bMake;
myCar.setYear(bYear);
cout << "You entered the year of the car as " << myCar.getYear() << endl;
myCar.setMake(bMake);
cout << "You entered the make of the car as " << myCar.getMake() << endl;
int i = 0;
for (; i<5; ++i)
{
myCar.accelerate();
cout << "Accelerating.\n" << "The current speed of the car is: " << myCar.getSpeed() << endl;
}
{
int j = 0;
for (; j<5; ++j)
{
myCar.brake();
cout << "Decelerating.\n" << "The current speed of the car is: " << myCar.getSpeed()<<endl;
}
}
}
【问题讨论】:
-
你能编辑你的文本/代码吗,真的很难读
-
我把指令间隔得更远了。
标签: c++ class constructor