Why do stream operators return references in C++?

前端 未结 2 1648
谎友^
谎友^ 2021-01-19 17:33

I know that indexing operator implementations usually return references so that the values can be set as well as retrieved, but why do streams?

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 18:13

    Streams do not support copying or assignment, so anything that passes or returns a stream must use either a pointer or reference. You can't use overloaded operators on a pointer (without dereferencing it) because they'd try to apply the built-in operator to the pointer itself.

    So, returning a reference is the only choice that supports operator chaining.

提交回复
热议问题