我是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参数构造函数没有被调用。

关于c++ - 重载>>时未获得期望值。我在这里做错了什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33993445/

10-12 07:32