【问题标题】:Arithmetic and Relational Operators算术和关系运算符
【发布时间】: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


【解决方案1】:

问题出在您的代码中。

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

您不应该在 cout 中使用 cout。你的打印语句应该是这样的

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

希望这会有所帮助。 谢谢。

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 2012-03-21
    • 2022-01-07
    • 2021-03-05
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多