将这个c ++代码分解为单独的类规范文件和函数定义文件?

时间:2013-08-31 21:12:48

标签: c++

作业要求我写一个名为car的类,创建一个汽车对象,让它加速并制动5x每个5x。这已经完成了,但我想将函数和类定义与main.cpp分开......我想我还没有完全理解如何做到这一点。

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// Car class declaration.

class Car 
{
    private:
    // member variables
    int yearModel;
    string make;
    int speed;

    public:
    Car(int carYearModel, string carMake, int carSpeed)
    { yearModel = carYearModel;
      make = carMake;
      speed = carSpeed; }

    void accelerate(int mph)
    { speed += mph; }
    void brake(int mph)
    { speed -= mph; }

    int getSpeed () const
    { return speed; }
};

int main()
    {
    int count;
    Car honda(2005, "Accord", 0);

    cout << "The starting speed is "  
     << honda.getSpeed() << endl << endl;

    cout << "We will now accelerate by 5 mph, 5 times.\n";
    system ("pause");

    for ( count = 0; count < 5; count++)
    {
        honda.accelerate(5);
        cout << "Speed is now: " << honda.getSpeed() 
             << " mph." << endl;
    }

    system ("pause");

    cout << endl << "Now we will brake by 5 mph, 5 times. \n";
    system ("pause");

    for ( count = 0; count < 5; count++)
    {
        honda.brake(5);
        cout << "Speed is now: " << honda.getSpeed() 
             << " mph." << endl;
    }

    system ("pause");

    return 0;
    }

1 个答案:

答案 0 :(得分:1)

  • 从定义中拆分声明。
  • 将定义移至cpp文件
  • 将声明移至hpp文件

最重要的是

  • 从不在标头文件中使用using namespace

Car.hpp:

#ifndef CAR_INCLUDED_H
#define CAR_INCLUDED_H
#include <string>

class Car 
{
    private:
        int yearModel;
        std::string make;
        int speed;

    public:
        Car(int carYearModel, std::string carMake, int carSpeed);
        void accelerate(int mph);
        void brake(int mph);
        int getSpeed () const;
};

#endif

Car.cpp:

#include "Car.hpp"

Car::Car(int carYearModel, std::string carMake, int carSpeed)
{
    yearModel = carYearModel;
    make = carMake;
    speed = carSpeed;
}

void Car::accelerate(int mph)
{
    speed += mph;
}
void Car::brake(int mph)
{
    speed -= mph;
}

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

main.cpp中:

#include "Car.hpp"

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int count;
    Car honda(2005, "Accord", 0);

    cout << "The starting speed is "  
        << honda.getSpeed() << endl << endl;

    cout << "We will now accelerate by 5 mph, 5 times.\n";
    system ("pause");

    for ( count = 0; count < 5; count++)
    {
        honda.accelerate(5);
        cout << "Speed is now: " << honda.getSpeed() 
            << " mph." << endl;
    }

    system ("pause");

    cout << endl << "Now we will brake by 5 mph, 5 times. \n";
    system ("pause");

    for ( count = 0; count < 5; count++)
    {
        honda.brake(5);
        cout << "Speed is now: " << honda.getSpeed() 
            << " mph." << endl;
    }

    system ("pause");

    return 0;
}