我一直有错误,我不确定如何将此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的类,该类具有以下成员 变量:
在创建Car对象的程序中演示该类,然后 调用加速功能5次。每次调用加速功能后, 获得当前的汽车速度并显示它。然后,拨打刹车 功能5次。每次调用break函数后,获取当前速度 汽车并显示它。
答案 0 :(得分:1)
更改
Car(){
int year = 1990;
std::string make = "Bentley";
int speed = 0;
};
到
Car(){
year = 1990;
make = "Bentley";
speed = 0;
}
您不需要在此处指定数据类型。
下,
std::cout << "Year: " << YourCar.get_year << std::endl;
std::cout << "Make: " << YourCar.get_make << std::endl;
std::cout << "Speed: " << YourCar.get_speed << std::endl;
应该是
std::cout << "Year: " << YourCar.get_year() << std::endl;
std::cout << "Make: " << YourCar.get_make() << std::endl;
std::cout << "Speed: " << YourCar.get_speed() << std::endl;
你在功能之后忘记了()
。