C ++类 - 使用x和y坐标查找汽车距离

时间:2017-05-01 05:23:26

标签: c++ constructor

我试图找出如何处理我的代码。我需要找出出租车的x和y值,看看出租车相对于出租车随x和y方向移动的距离。

第一个输出是正确的,移动了8个空格。但是第二个输出始终不正确。它相对于出租车的当前位置输出7,但它应该位于-1。

我知道在我输入重载的构造函数时出错。使用数组和指针有一个答案,但我还没有在课堂上学到这一点。我希望看到另一种选择。

#ifndef TAXICAB_CPP
#define TAXICAB_CPP

class Taxicab
{
private:
    int xCoord;
    int yCoord;
    int totalDistance;
public:
    //constructors
    Taxicab(); //default constructor
    Taxicab(int, int); //overload constructor

    //accessors
    int getX(); //returns X
    int getY(); //returns Y
    int getDistanceTraveled();

    //mutators
    void moveX(int); //moves X 
    void moveY(int); //moves Y
};
#endif


//#include "Taxi.h" will need to divide the header file
#include <iostream> 
#include <cmath>

using namespace std;

Taxicab::Taxicab() //default constructor
{
    xCoord = 0;
    yCoord = 0;
    totalDistance = 0;
}

 Taxicab::Taxicab(int xCoord, int yCoord) //overload constructor
{
    //this->xCoord = xCoord; // while this works I cannot enter code with things I haven't learned yet.
    //this->yCoord = yCoord;
    totalDistance = 0;
}

int Taxicab::getX()
{
    return xCoord;
}

int Taxicab::getY()
{
    return yCoord;
}

void Taxicab::moveX(int X)
{
    totalDistance += abs(X);
    xCoord += X;
}

 void Taxicab::moveY(int Y)
{
     totalDistance += abs(Y);
     yCoord += Y;
}

int Taxicab::getDistanceTraveled()
{
    return totalDistance;
}

int main()
{
    Taxicab cab1;
    Taxicab cab2(5, -8);
    cab1.moveX(3);
    cab1.moveY(-4);
    cab1.moveX(-1);
    cout << cab1.getDistanceTraveled() << endl;
    cab2.moveY(7);
    cout << cab2.getY() << endl;
}

0 个答案:

没有答案