重载>>时未获得预期值。我在这里做错了什么?

Not getting the expected value while overloading >>. What am I doing wrong here?

本文关键字:gt 在这里 什么 错了 重载      更新时间:2023-10-16

我是C++的初学者,正在学习它。我现在正在研究运算符重载。在下面的代码中,我重载了>>以获得类值作为输入。但是,我无法像构造函数中描述的那样转换值。当它被转换为构造函数内部的编码时,有什么方法可以做吗。以下是我的代码:

#include <iostream>
using namespace std;
class Time
{
private:
    int hour;
    int minute;
    int second;
public:
    Time()
    {
        Time(0,0,0);
    }
    Time(int hh, int mm, int ss)
    {
        second = ss%60;
        mm +=ss/60;
        minute = mm%60;
        hh +=mm/60;
        hour = hh;
    }
    friend istream& operator>>(istream &in, Time &t1);
    int GetHour()    {        return hour;    }
    int GetMinute()     {        return minute;    }
    int GetSecond()     {        return second;    }
};
istream& operator >>(istream &in, Time &tm)
{
    in >> tm.hour;
    in >> tm.minute;
    in >> tm.second;
    return in;
}
int main()
{
    using namespace std;
    Time tm;
    cin >> tm;
    cout << tm.GetHour() << ":" << tm.GetMinute() << ":" << tm.GetSecond();
    return 0;
}

在上面的例子中,无论我输入什么值,都会作为输出而不是构造函数中的语句打印出来。

默认情况下,您正在构造tm,然后使用重载运算符填充其中的字段。您的3参数构造函数不会被调用。