【问题标题】:(C++ Beginner) How do I call these class functions into the main? [closed](C++初学者)如何将这些类函数调用到main中? [关闭]
【发布时间】: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 的类,该类具有以下成员 变量:

  1. 年。保存汽车型号年份的 int。
  2. 制作。一个包含汽车品牌的字符串对象。
  3. 速度。保存汽车当前速度的 int。 此外,该类应具有以下成员函数:
  4. 构造函数。构造函数应接受汽车的年份并制作 作为参数并将这些值分配给对象的年份并使 成员变量。构造函数应该初始化速度成员 变量为 0。
  5. 访问器或吸气剂。适当的访问器或吸气剂应该允许 要从对象的年份、品牌和速度成员中检索的值 变量。
  6. 加速。加速函数应该给速度成员加 5 每次调用时变量。
  7. 刹车。制动功能应从速度成员中减去 5 每次调用时变量。

在创建 Car 对象的程序中演示该类,然后 调用加速函数 5 次。每次调用加速函数后, 获取汽车的当前速度并显示它。然后,叫刹车 功能5次。每次调用break函数后,获取当前速度 汽车并展示它。

【问题讨论】:

  • 自己做作业。如果您有具体问题,请用能代表您的问题的最小案例进行描述。
  • Alex,学期末了,哥们。你得做好功课。但是,首先初始化类, Car *car = new Car();
  • 这个构造函数就像用 JavaScript 写的一样。 C++(和大多数其他语言)的工作方式非常不同。
  • @JaredBurrows 不,那是 Java。他至少正确地创建了Car
  • 哇 @alex... 与他人交谈的方式真棒。

标签: c++ function class oop


【解决方案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;

你忘记了函数后面的()

【讨论】:

  • 我不认为 C++ 真的会抱怨分号太多。
  • 我想实际上构造函数可能应该接受参数而不是初始化所有汽车。
  • 构造函数重载。
  • @Wug 啊,我明白了,对不起。
  • 谢谢,我想这就是我解决此问题所需的全部帮助。
猜你喜欢
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
  • 2014-09-10
  • 2013-04-27
  • 2013-02-03
  • 2013-01-02
相关资源
最近更新 更多