C ++构造函数Car Class

时间:2016-11-12 19:54:39

标签: c++ performance function object constructor

大家好,我在下面的任务中遇到了一些麻烦。当我运行代码时,一切似乎都有效,但我在打印输出中得到的数字并不准确。不确定它是否是我的构造函数设置错误或什么。我一直在撞墙试图解决这个问题。任何帮助/建议将不胜感激!

以下是作业文字:

汽车类说明:写一个名为' Car'具有以下成员变量:

年。一个持有汽车模型年的int。

请。一个字符串对象,用于保存汽车的品牌。

速度。保持汽车当前速度的int对象。

此外,该类应具有以下成员函数:

构造。构造函数应该接受汽车的年份并制作成员变量。构造函数应该将这些值初始化为对象的年份并生成成员变量。构造函数应该将速度成员变量初始化为0.

存取器。应创建适当的访问器函数,以允许从对象的年份,制造和加速成员变量中检索值。

加速。加速函数应在每次调用时向速度成员变量添加5。

刹车。每次调用时,制动功能应从速度成员变量中减去5。在创建Car对象的程序中演示类,然后调用加速函数五次。每次调用加速功能后,获取当前车速并显示。然后,调用制动功能5次。每次调用制动功能后,获取当前车速并显示它。

#include <iostream>
#include <string>

using namespace std;
class Car
{
  private:
    int year;
    string make;
    int speed;

  public:
    Car(int, string, int);
    int getSpeed();
    int getModel();
    void accelerate();
    void brake();


};

int Car::getSpeed()
{
    return speed;
}

Car::Car(int year, string make, int speed = 0 )
{
}

void Car::accelerate()
{
    speed +=5;
}

void Car::brake()
{
    if( speed > 5 )
        speed -=5;
    else speed = 0 ;
}


int main ()
{
    int year;
    string make;
    cout << "Please enter the model year of the car.\n";
    cin >> year ;
    cout << "Please enter the make of the car.\n";
    cin >> make ;

    Car myCar(year,make);
    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;
        }

        return (0);
    }
}

3 个答案:

答案 0 :(得分:1)

此构造函数

Car::Car(int year, string make, int speed = 0 )
{
}

没有初始化。它有一个空体,没有初始化成员列表。此外,根据赋值,构造函数必须有两个参数。

它可以看作以下方式

在课程定义中

inline Car( int year, std::string & make );

以及构造函数本身的定义

Car::Car( int year, const std::string make ) : year( year ), make( make ), speed( 0 )
{
}

可以将访问器声明为

int getYear() const;
int getSpeed() const;
const std::string & getModel() const;
^^^^^^^^^^^^^^^^^^^

答案 1 :(得分:1)

构造函数

Car::Car(int year, string make, int speed = 0 )
{
}

没有做你所描述的。这三个参数(yearmakespeed)与Car成员的名称相同,但它们是单独的变量。

结果是Car成员是默认构造的,main()传递的值实际上被忽略了。

为了使事情更清楚,请为参数指定不同的名称,并在初始化列表中初始化成员。

Car::Car(int y, string m, int s) : year(y), make(m), speed(s)
{
}

允许参数与类成员具有相同的名称,但这往往更难以阅读,即更容易误解代码正在做什么。在您的情况下,您认为给出与类成员同名的参数用于初始化类成员,这是完全错误的。无论哪种方式,构造函数都需要使用参数显式初始化成员,否则类成员会接收默认值(而不是传递的值)。

此外,如果您希望参数具有默认值,请在类的定义中指定它,而不是在构造函数的定义中指定。例如;

class Car
{
      public:

          Car(int, std::string, int = 0);
};

Car::Car(int y, string m, int s) : year(y), make(m), speed(s)
{
}

这使事情变得更容易,特别是如果类定义在头文件中。

答案 2 :(得分:0)

    #include "stdafx.h"
    #include <iomanip>
    #include <iostream>
    #include<stdio.h>
    #include <cstdlib>
    #include <string>
    #include <iomanip>
    double getaccelarate(double &, double &);
    double getbrake(double &, double &);
    double getcruise(double &, double &);
    void outputStatusHeader();
    void demo();
    double updateDistanceTraveled(double &, double &);
    int delta = 5;
    //double brakee = 0;


    double previousSpeed = 0;
    double currentSpeed = 0;


    using namespace std;


    int main()
    {
        char  command;
        //The amount of elapsed time for each calculation interval 
    (fixed at 1 second)
        const int timeInterval = 1;


        //double currentSpeed=0;
        //convert into the distance travelled by feet
        int    totalFeetTraveled = 0;
        //the average speed travel
        int averageSpeed = 0;


        //double previousSpeed =0;
        int averageSpeed_FeetPerSecond = 0;
        int  intervalFeetTraveled = 0;
        int speed = 0;
        //the amount of time that the time will increase by
        //const int delta= 5;




        while (true)
        {
                cout << "Command:";
                cin >> command;
                switch (command)
            {


            case 'a':
               //double accelarate;
                double speed;
                speed = getaccelarate(currentSpeed, previousSpeed);
              //cout << getaccelarate;
                cout << "Accelerate"<<setw(20)<<"Accelerating"<<setw(5);
                cout << speed;
                double conve;
                conve = updateDistanceTraveled(previousSpeed, 
    currentSpeed);
                    cout <<setw(10)<<setprecision(3)<<conve<<endl;

                //updateDistanceTraveled(previousSpeed,currentSpeed);
                break;





            case 'b':
                 double brake;
                 brake = getbrake(previousSpeed, currentSpeed);
                 cout << "Brake" <<setw(20)<<"Braking"<<setw(5);
                 cout << brake; 
                //double brake1 = 0;
                //brake1 = updateDistanceTraveled(previousSpeed, 
                 currentSpeed);
                 cout << setw(10) << setprecision(3) << conve << endl;




                break;

            case 'c':
                 double cruise;
                 cruise = getcruise(previousSpeed, currentSpeed);
                 cout << "Cruise" << setw(20) << "Cruising" << setw(5);
                 cout << cruise;
                 cout << setw(10) << setprecision(3) << conve << endl;


            break;




        case 'h':
            outputStatusHeader();
            break;

        case 'd':

            demo();

            break;
        case 'q':
            cout << " Exit program";
            exit(1);

            break;

        default:
            cout << "Invalid command" << endl; 
            break;
        }



    }




    system("pause");
    return 0;
}
//converting mph to feet perhours
double updateDistanceTraveled(double &previousSpeed,double &currentSpeed)
{
    //getaccelarate(previousSpeed, currentSpeed);
    double averageSpeed = 0; 
    double averageSpeed_FeetPerSecond = 0; 
    double intervalFeetTraveled=0;
    //double totalFeetTraveled=0;
    const int timeInterval = 1;

    averageSpeed = (previousSpeed + currentSpeed) / 2;
    averageSpeed_FeetPerSecond = averageSpeed * 5280.0 / 3600.0;
    intervalFeetTraveled = averageSpeed_FeetPerSecond * timeInterval;
    return intervalFeetTraveled;
    /*totalFeetTraveled = totalFeetTraveled + intervalFeetTraveled;
    return totalFeetTraveled;*/
}

//to decrease speed
double getbrake(double &previousSpeed, double &currentSpeed)
{



    previousSpeed = currentSpeed;
    currentSpeed -= delta;

    return currentSpeed;


}
//to increase speed
double getaccelarate(double &previousSpeed, double &currentSpeed)
{


    previousSpeed = currentSpeed;
    currentSpeed = currentSpeed + delta;
    return currentSpeed;


}

// to stay in current speed
double getcruise(double &previousSpeed, double &currentSpeed)
{
    previousSpeed = currentSpeed;
    return previousSpeed;

}
//unfinished demo

void demo()

{

    cout << "Function Current State Current Speed Interval Distance 
    Total Feet (and miles) traveled" << endl;

    cout << "-----------------------------------------------------------------------------------" << endl;

    for (int x = 1; x < 4; x++)
    {
        double speed;
        speed = getaccelarate(currentSpeed, previousSpeed);
        //cout << getaccelarate;
        cout << "Accelerate" << setw(20) << "Accelerating" << setw(5);
        cout << speed;
        double conve;
        conve = updateDistanceTraveled(previousSpeed, currentSpeed);
        cout << setw(10) << setprecision(3) << conve << endl;

    }

}

//for supported commands
void outputStatusHeader()

{

    cout << " supported commands\n"
        << " a         accelerate\n"
        << " b         brake\n"
        << " c         cruise\n"
        << " d         demo\n"
        << " h         print this help text\n"
        << " q         quit(end the  program)"
        << endl;

}

{

        cout << " supported commands\n"
            << " a         accelerate\n"
            << " b         brake\n"
            << " c         cruise\n"
            << " d         demo\n"
            << " h         print this help text\n"
            << " q         quit(end the  program)"
            << endl;

}