我跟着我的书到了T,出于某种原因,当我尝试运行我的程序时,操作员和操作员+的输出完全错误输出。你知道我的重载操作符和我重载的操作符+出了什么问题。该程序编译良好,但输出不正确。
#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;
}
答案 0 :(得分:0)
问题在于您的代码。
cout <<"First + Second = " << cout << third.gethours() << endl;
你不应该在cout中使用cout。您的打印声明应该是这样的
cout <<"First + Second = " << third.gethours() << endl;
希望这会有所帮助。 谢谢。