为什么我的计算结果不对? 1个工作日应该等于8个小时。

时间:2016-02-20 00:06:15

标签: c++ class c++11 object operator-overloading

我认为我的数学并没有在setter函数中完成。我一直盯着它看太久了。在此先感谢程序员!

#include <iostream>
using namespace std;

class numDays
{
int hours;  
int days;

public:
numDays(int hrs); //constructor prototype
void setHours(int);
void setDays(int);
int  getHours();
int  getDays();

double operator+ (const numDays Object1) //overloading the + operator to   return the sum of two objects' hours members
{
return hours + Object1.hours;
}

double operator-(const numDays Object1) //overloading the + operator to     return the difference of two objects' hours members
{
return hours - Object1.hours;
}

numDays operator++() //prefix increment operator to increment # of hours   stored in object. Days are recalculated.
{
++hours;
days = hours/8;
return *this;
}

numDays operator++(int) //postfix increment operator to increment # of hours stored in object. Days are recalculated.
{
numDays temp(hours);
hours++;
days = hours/8;
return temp;
}

numDays operator--() //prefix decrement operator to decrement # of hours stored in object. Days are recalculated.
{
--hours;
days = hours/8;
return *this;
}

numDays operator-- (int) //prefix decrement operator to decrement # of     hours stored in object. Days are recalculated.
{
numDays temp(hours);
hours--;
days = hours/8;
return temp;
}

};

numDays::numDays(int hrs) //constructor that accepts a number of hours
{hours = hrs;}

我希望问题出现在setHours函数或setDays函数中。

void numDays::setHours(int hrs) //mutator function to store the amount of  hours
{
hours = hrs;
days = hrs/8;
}

void numDays::setDays(int d) //mutator function to store the amount of days
{
hours = d;
days = hours % 8;
}

int numDays::getHours() //accessor function to get the amount of hours
{
return hours;
}

int numDays::getDays() //accessor function to get the amount of days
{
return days;
}


int main()
{
int workHours;

numDays object2(0);

cout << "Please type in a certain amount of hours to see how much work in  days it is: ";
cin >> workHours;

object2.setHours(workHours);
object2.setDays(workHours);

cout << "The number of hours you put in is " << object2.getHours() << endl;
cout << "That means you worked " <<object2.getDays() << " days " << endl;

return 0;
}

1 个答案:

答案 0 :(得分:2)

也许我不能正确理解setDays()的意图,但看起来这就是你想要的:

void numDays::setDays(int d) //mutator function to store the amount of days
{
    days = d;
    hours = days * 8;
}