What is the purpose of this block of code?

Today in class, my professor put the following code up in class, and it really confused me. I think he said it would change something within cout << but I'm not really sure. I know there's code missing here, but I don't think its needed, just wanting a quick little explanation if anyone knows. Thanks.

1
2
3
4
5
6
7
8
9
10
11
  std::ostream& operator << (std::ostream& out, const ListType& list) {
   if (list.count != 0) {
    std::cout<<list.list[0];
      for (size_t I=; I<list.count; ++i) {
       std::cout<<", " <<list.list[i];
     }
}

return out;
}
This is an overload for operator<< that will print list on out.

std::cout is a type of std::ostream so it may serve as the ostream on which the operator is invoked, meaning that code like this:

1
2
    ListType myList;
    std::cout << myList << '\n' ;


will do what one would expect.
... but code like this:
1
2
3
    ListType myList;
    std::ofstream fout ("output.txt");
    fout << myList << '\n' ;

would not do what one would expect. That is to say, it would still show the output on std::cout, rather than the specified stream fout.

I think there are a couple of typos in the original code, it might look more like this:
1
2
3
4
5
6
7
8
9
10
11
std::ostream& operator << (std::ostream& out, const ListType& list) {

    if (list.count != 0) {
        out << list.list[0];
        for (size_t i=1; i<list.count; ++i) {
            out << ", " << list.list[i];
        }
    }

    return out;
}


Good catch. I glossed over it.
Topic archived. No new replies allowed.