-1

I have a class called Length which holds hours, mins and secs. It has an overloaded >> operator for parsing input to the object:

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;
}

Now I'm trying to write a class, which holds a Length, and a Title (for movies):

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;
}

I'd like to overload this >> operator too, to get input converted to a Title and a Length object.

Is there a way to use the >> overload I wrote in Length, inside the Movie overloaded >> operator? All I've got so far:

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

1 Answers1

2

Is there a way to use the >> overload I wrote in Length, inside the Movie overloaded >> operator?

Yes all you need to do is to call it, as in

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

However, you dont need this additional instance. There already is a title and a length in the d you pass to the operator. You better make the operator a friend of Movie (via adding friend std::istream& operator>>(std::istream&,Movie&); to the declaration of Movie). Then you can write

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

For more details on operator overloading see here: What are the basic rules and idioms for operator overloading?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185