【发布时间】:2016-07-04 10:02:52
【问题描述】:
我跟着我的书到了 T,由于某种原因,当我尝试运行我的程序时,我得到了完全错误的 operator- 输出和 operator+ 的输出。你知道我的重载运算符和我的重载运算符+出了什么问题吗?程序编译得很好,但输出根本不对。
#include <iostream>
using namespace std;
class NumDays
{
private:
int ptrHours;
public:
NumDays(int H)// to set the pointer
{ setHours(H);}
void setHours(int H)
{ptrHours = H;}
int gethours() {return ptrHours;}
double calcDays()// function to calculate the days
{
double days;
days = ptrHours/8.0;
return days;
}
friend NumDays operator+(NumDays a, NumDays b);
friend NumDays operator-(NumDays a, NumDays b);
};
NumDays operator+(NumDays a, NumDays b)
{
return NumDays(a.ptrHours + b.ptrHours);
}
NumDays operator-(NumDays a, NumDays b)
{
return (a.ptrHours - b.ptrHours);
}
int main ()
{
NumDays first(0),
second(0),
third(0);
int hours1, hours2;
cout <<"Enter the how many hours you worked..." << endl;
cout <<"First set: ";
cin >> hours1;
while (hours1 < 0)
{
cout <<"\nYou cannot enter a negative value. " << endl;;
cin >> hours1;
}
first.setHours(hours1);
cout <<"Second Set: ";
cin >> hours2;
while (hours1 < 0)
{
cout <<"\nYou cannot enter a negative value. " << endl;;
cin >> hours2;
}
second.setHours(hours2);
cout <<"First set for days worked is " << first.calcDays() <<" days." << endl;
cout <<"Second set for days worked is " << second.calcDays() <<" days." << endl;
third = first - second;// where I try and do my arithmetic operators
cout <<"First - Second = " << cout << third.gethours() << endl;
third = first + second;
cout <<"First + Second = " << cout << third.gethours() << endl;
cin.ignore();
cin.get();
return 0;
}
【问题讨论】:
-
你得到了什么输出,你期望什么?请编辑您的问题以包含该问题(将实际输出复制粘贴到问题正文中)。
-
请格式化。另外,should not compile.
-
另外,删除示例中不需要重现问题的部分。
-
在一个完全不相关的问题上,
ptrHours这个名字有点误导,因为ptr通常是指针的缩写,而变量绝对不是指针。 -
当问题陈述很简单时,很难提供解决方案,“它不起作用”。请edit您的问题更完整地描述您预期会发生什么以及这与实际结果有何不同。请参阅 How to Ask 以获取有关什么是好的解释的提示。
标签: c++ oop operator-overloading