在另一个C ++类中使用对象的重载istream

时间:2019-04-16 09:49:22

标签: c++

我有一个名为Length的课程,其中包含小时,分钟和秒。它具有重载的>>运算符,用于解析对象的输入:

istream& operator>>(istream& is, Length &t) {
    char c1, c2;

    int hours, mins, secs;

    if (is >> hours >> c1 >> mins >> c2 >> secs) {
        if (c1 == c2 == ':') {
            t = Length(hours, mins, secs);
        }
        else {
            is.clear(ios_base::failbit);
        }
    }
    return is;
}

现在,我正在尝试编写一个类,其中包含一个Length和一个Title(对于电影):

class Movie {
    string title;
    Length length;

public:
    Movie();
    Movie(string title, Length length);
    string getTitle() const;
    Length getLength() const;
    operator int() const;
};

inline Movie::Movie() {
    this->title = "New Movie";
    this->length = Length();
}

inline Movie::Movie(string title, Length length) {
    this->title = title;
    this->length = length;
}

我也想重载此>>运算符,以将输入转换为TitleLength对象。

>>重载的Length运算符内部,有没有办法使用我在Movie中写的>>重载?到目前为止,我所拥有的:

istream& operator>>(istream& is, Movie &d) {
    string title;
    Length length;
    /*Not sure how to code this*/
    return is;
}

1 个答案:

答案 0 :(得分:2)

  

有没有一种方法可以使用我在Length中写的>>重载,   电影超载>>运算符?

是的,您需要做的就是调用它,如

istream& operator>>(istream& is, Movie &d) {
    string title;
    Length length;
    is >> title >> length;
    d = Movie(title,length);
    return is;
}

但是,您不需要此其他实例。您传递给运算符的title中已经有一个length和一个d。最好使运算符成为Movie的朋友(通过在friend std::istream& operator>>(std::istream&,Movie&);的声明中添加Movie)。然后你可以写

istream& operator>>(istream& is, Movie &d) {
    is >> d.title >> d.length;
    return is;
}

有关运算符重载的更多详细信息,请参见此处:What are the basic rules and idioms for operator overloading?