算术和关系运算符

Arithmetic and Relational Operators

本文关键字:运算符 关系      更新时间:2023-10-16

我按照我的书到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;
}

问题出在你的代码中。

cout <<"First + Second = " << cout << third.gethours() << endl;

你不应该在cout中使用cout。你的print语句应该像这样

cout <<"First + Second = " << third.gethours() << endl;

希望这将帮助。谢谢你。