重载>>运算符未在输入上设置属性

Overloading >> operator is not setting attributes on input

本文关键字:gt 设置 属性 输入 运算符 重载      更新时间:2023-10-16

我是C++新手,并试图通过重载>> 运算符从 cin 读入我的对象。但是,输入后,我创建的对象保持不变。

页眉:

class Duration {
private:
    int hours, mins, secs;
public:
    Duration();
    Duration(int hours, int mins, int secs);
};
inline Duration::Duration() {
    this->hours = 0;
    this->mins = 0;
    this->secs = 0;
}
inline Duration::Duration(int hours, int mins, int secs) {
    this->hours = hours;
    this->mins = mins;
    this->secs = secs;
}
inline istream& operator>>(istream& is, Duration &d) {
    char c1, c2;
    int hours, mins, secs;
    if (is >> hours >> c1 >> mins >> c2 >> secs) {
        if (c1 == c2 == ':') {
            d = Duration(hours, mins, secs);
        }
        else {
            is.clear(ios_base::failbit);
        }
    }
    return is;
}
inline ostream& operator<<(ostream& os, const Duration &d) {
    return os << d.getHours() << ":"
              << d.getMins() << ":"
              << d.getSecs();
}

和我的主要:

int main(int argc, char** argv) {
    Duration test;
    cin >> test;
    cout << test << endl;
    return EXIT_SUCCESS;
}

我很确定我已经在需要时包含了所有"通过引用"指示,我不确定我做错了什么。无论我在运行程序时输入什么,生成的Duration test都具有值 0:0:0

if (c1 == c2 == ':')

所指出的问题,评估true == ':'哪个当然等于false。我用if (c1 == c2 && c2 == ':')修复了它(不确定是否最有效,但现在肯定按预期工作(。