【发布时间】:2015-04-29 04:53:01
【问题描述】:
我一直有错误,我不确定如何将这个 Car 类调用到主函数中。我得到的说明如下。
#include <iostream>
#include <string>
class Car{
public:
Car(){
int year = 1990;
std::string make = "Bentley";
int speed = 0;
};
Car(int new_year, std::string new_make, int new_speed) {
year = new_year;
make = new_make;
speed = new_speed;
}
int get_year() { return year; }
std::string get_make() { return make; }
int get_speed() { return speed; }
void accelerate() {
speed+=5;
}
void brake() {
speed-=5;
}
private:
int year;
std::string make;
int speed;
};
int main()
{
int year = 1990;
std::string make = "Bentley";
int speed = 0;
Car YourCar(year, make, speed);
std::cout << "Year: " << YourCar.get_year << std::endl;
std::cout << "Make: " << YourCar.get_make << std::endl;
std::cout << "Speed: " << YourCar.get_speed << std::endl;
}
说明: 请在 C++ 中实现一个名为 Car 的类,该类具有以下成员 变量:
- 年。保存汽车型号年份的 int。
- 制作。一个包含汽车品牌的字符串对象。
- 速度。保存汽车当前速度的 int。 此外,该类应具有以下成员函数:
- 构造函数。构造函数应接受汽车的年份并制作 作为参数并将这些值分配给对象的年份并使 成员变量。构造函数应该初始化速度成员 变量为 0。
- 访问器或吸气剂。适当的访问器或吸气剂应该允许 要从对象的年份、品牌和速度成员中检索的值 变量。
- 加速。加速函数应该给速度成员加 5 每次调用时变量。
- 刹车。制动功能应从速度成员中减去 5 每次调用时变量。
在创建 Car 对象的程序中演示该类,然后 调用加速函数 5 次。每次调用加速函数后, 获取汽车的当前速度并显示它。然后,叫刹车 功能5次。每次调用break函数后,获取当前速度 汽车并展示它。
【问题讨论】:
-
自己做作业。如果您有具体问题,请用能代表您的问题的最小案例进行描述。
-
Alex,学期末了,哥们。你得做好功课。但是,首先初始化类, Car *car = new Car();
-
这个构造函数就像用 JavaScript 写的一样。 C++(和大多数其他语言)的工作方式非常不同。
-
@JaredBurrows 不,那是 Java。他至少正确地创建了
Car。 -
哇 @alex... 与他人交谈的方式真棒。