使用C ++类计算汽车的移动和距离

时间:2017-04-15 05:11:25

标签: c++

然而,这个程序编译,我需要让这个功能移动到x& y坐标然后输出行进的总距离。当yCord上下移动时,xCord左右移动它。我想我需要更新我的int Taxicab :: getDistanceTraveled(),void Taxicab :: moveX(int getX),& void Taxicab :: moveX(int getX)。但是对于我的生活来说无法弄清楚要做些什么来让它正确更新。当我编译并运行时,它给我132617596用于cab1行驶距离和0用于cab2上的Y坐标。谢谢您的帮助!

#ifndef TAXI_CPP
#define TAXI_CPP

class Taxicab
{
private:
    int xCord;
    int yCord;
    int totalDist;
public:
    Taxicab(); //default constructor
    Taxicab(int, int); //overload constructor
    int getX(); //returns X coordinate
    int getY(); //returns Y coordinate
    int getDistanceTraveled(); //returns distance calculation
    void moveX(int); //moves X left or right
    void moveY(int); //moves Y left or right 
};
#endif // !TAXI_CPP




#include "Taxi.h"
#include <iostream> 
#include <math.h>
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;
using std::abs;

Taxicab::Taxicab() //default constructor
{

}

Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
    xCord = 0; //initialize to 0
    yCord = 0; //initialize to 0
    totalDist = 0; //initialize to 0
}

int Taxicab::getX()
{
    return xCord; //return x coordinate
}

int Taxicab::getY()
{
    return yCord; //return y coordinate
}

void Taxicab::moveX(int getX)
{
    int moveX = 0;
    moveX = moveX + getX;
}

void Taxicab::moveY(int getY)
{
    int moveY = 0;
    moveY = moveY + getY;
}

int Taxicab::getDistanceTraveled()
{
    return abs(xCord) + abs(yCord);
}


#include <iostream>
#include "Taxi.h"
#include <math.h>

using std::cout;
using std::cin;
using std::endl;

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;
}

1 个答案:

答案 0 :(得分:2)

你的构造函数没有意义。 在默认构造函数中,您必须将成员变量初始化为某些内容,否则它们的值是未定义的,可以设置为某个随机值。试试这些:

Taxicab::Taxicab() //default constructor
{
    xCord = 0; //initialize to 0
    yCord = 0; //initialize to 0
    totalDist = 0; //initialize to 0
}

Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
    this->xCord = xCord;
    this->yCord = yCord;
    totalDist = 0; //initialize to 0
}

移动出租车的方法也没有多大意义。也许这样的事情会更好:

void Taxicab::moveX(int offsetX)
{
    totalDist += abs(offsetX);
    xCoord += offsetX;
}

void Taxicab::moveY(int offsetY)
{
    totalDist += abs(offsetY);
    yCoord += offsetY;
}

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