C++ 算术和关系运算符

C++ 算术和关系运算符,c++,oop,operator-overloading,C++,Oop,Operator Overloading,我跟着我的书走到T,由于某种原因,当我尝试运行我的程序时,我得到了完全错误的运算符输出,而运算符+是我的输出。你知道我的重载运算符-和重载运算符+-出了什么问题吗。程序编译得很好,但输出根本不正确 #include <iostream> using namespace std; class NumDays { private: int ptrHours; public: NumDays(int H)// to set

我跟着我的书走到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 <<"First + Second = " << third.gethours() << endl;
希望这会有所帮助。
谢谢。

您得到了什么样的输出,您期望得到什么?请编辑您的问题以包含该副本,并将实际输出粘贴到问题正文中。请设置格式。此外,。另外,删除示例中不需要重现问题的部分。在一个完全不相关的问题上,名称ptrHours有点误导,因为ptr通常是指针的缩写,变量肯定不是指针。当问题陈述很简单,它不起作用时,很难提供解决方案。请你的问题更完整地描述一下你预期会发生什么,以及这与实际结果有什么不同。请参阅,以获取关于什么是好的解释的提示。