Why do stream operators return references in C++?

前端 未结 2 1652
谎友^
谎友^ 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:20

    So you can chain them together.

    cout << "hello" << "how are you";
    

    Works because cout << "hello" returns a reference to the cout so that << "how are you" knows there to put itself.

    Most operators, such as +=, also do this.

提交回复
热议问题